>  기사  >  데이터 베이스  >  SpringBoot와 Redis를 통합하는 방법

SpringBoot와 Redis를 통합하는 방법

王林
王林앞으로
2023-05-30 12:03:40733검색

SpringBoot와 비관계형 데이터베이스 Redis의 통합

(1) Spring Data Redis 종속성 시작 프로그램 추가

SpringBoot와 Redis를 통합하는 방법

이 종속성을 도입하여 프로젝트를 생성하면 프로젝트 pom.xml 파일에 다음 종속성이 나타납니다.

SpringBoot와 Redis를 통합하는 방법

(2) 엔터티 클래스 작성

Person:

package com.hardy.springbootdataredis.domain;import org.springframework.data.annotation.Id;import org.springframework.data.redis.core.RedisHash;import org.springframework.data.redis.core.index.Indexed;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */@RedisHash("persons")   // 指定操作实体类对象在Redis数据库中的存储空间public class Person {

    @Id // 标识实体类主键private String id;

    @Indexed // 标识对应属性在Redis数据库中生成二级索引private String firstname;

    @Indexedprivate String lastname;private Address address;public String getId() {return id;
    }public void setId(String id) {this.id = id;
    }public String getFirstname() {return firstname;
    }public void setFirstname(String firstname) {this.firstname = firstname;
    }public String getLastname() {return lastname;
    }public void setLastname(String lastname) {this.lastname = lastname;
    }public Address getAddress() {return address;
    }public void setAddress(Address address) {this.address = address;
    }

    @Overridepublic String toString() {return "Person{" +
                "id='" + id + ''' +
                ", firstname='" + firstname + ''' +
                ", lastname='" + lastname + ''' +
                ", address=" + address +
                '}';
    }
}

Address:

package com.hardy.springbootdataredis.domain;import org.springframework.data.redis.core.index.Indexed;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */public class Address {

    @Indexedprivate String city;

    @Indexedprivate String country;public String getCity() {return city;
    }public void setCity(String city) {this.city = city;
    }public String getCountry() {return country;
    }public void setCountry(String country) {this.country = country;
    }

    @Overridepublic String toString() {return "Address{" +
                "city='" + city + ''' +
                ", country='" + country + ''' +
                '}';
    }
}

위의 두 엔터티 클래스에는 Redis 데이터베이스의 데이터 작업에 대한 여러 주석이 포함됩니다.

  • @RedisHash("persons ") : Redis 데이터베이스에서 운영 엔터티 클래스 객체의 저장 공간을 지정하는 데 사용됩니다. 여기서는 Person 엔터티 클래스에 대한 데이터 작업이 Redis 데이터베이스에서 person이라는 저장 공간에 저장된다는 의미입니다.

  • @Id: 엔터티 클래스의 기본 키를 식별하는 데 사용됩니다. Redis 데이터베이스에서는 고유한 엔터티 개체 ID를 나타내기 위해 기본적으로 문자열 형식의 HashKey가 생성됩니다. 물론 데이터 저장 중에 ID를 수동으로 지정할 수도 있습니다.

  • @Indexed: Redis 데이터베이스의 해당 속성에 대한 보조 인덱스를 생성하도록 지정하는 데 사용됩니다. 이 주석을 사용하면 해당 속성에 해당하는 보조 인덱스가 데이터베이스에 생성되므로 데이터 쿼리가 간단해집니다. 인덱스 이름은 속성 이름과 동일합니다.

(3) 쓰기 리포지토리 인터페이스

SpringBoot는 Redis를 포함한 일부 일반 데이터베이스에 대해 자동화된 구성을 제공합니다. 리포지토리 인터페이스를 구현하여 데이터베이스의 데이터 추가, 삭제, 확인 및 수정 작업을 단순화할 수 있습니다.

package com.hardy.springbootdataredis.repository;import com.hardy.springbootdataredis.domain.Person;import org.springframework.data.repository.CrudRepository;import java.util.List;/**
 * @Author: HardyYao
 * @Date: 2021/6/15 */public interface PersonRepository extends CrudRepository<Person, String> {

    List<Person> findByAddress_City(String City);

}

참고 : Redis 데이터베이스를 작동할 때 작성된 Repository 인터페이스 클래스는 JpaRepository를 상속하는 대신 가장 낮은 수준의 CrudRepository 인터페이스를 상속해야 합니다(JpaRepository는 SpringBoot의 JPA 통합에 고유합니다). 물론 SpringBoot에서 통합한 JPA 종속성과 Redis 종속성을 동시에 프로젝트 pom.xml 파일로 가져올 수도 있으므로 JpaRepository 인터페이스를 상속하는 인터페이스를 작성하여 Redis 데이터베이스를 작동할 수도 있습니다.

(4) Redis 데이터베이스 연결 구성

프로젝트의 전역 구성 파일 application.properties에 Redis 데이터베이스 연결 구성을 추가합니다. 샘플 코드는 다음과 같습니다.

# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=

(5) 쓰기 단위 테스트 방법

package com.hardy.springbootdataredis;import com.hardy.springbootdataredis.domain.Address;import com.hardy.springbootdataredis.domain.Person;import com.hardy.springbootdataredis.repository.PersonRepository;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;

@SpringBootTestclass SpringbootdataRedisApplicationTests {

    @Autowiredprivate PersonRepository repository;

    @Testpublic void savePerson() {
        Person person = new Person();
        person.setFirstname("张");
        person.setLastname("三");
        Address address = new Address();
        address.setCity("北京");
        address.setCountry("中国");
        person.setAddress(address);// 向Redis数据库添加数据Person save = repository.save(person);
    }

    @Testpublic void selectPerson() {
        List<Person> list = repository.findByAddress_City("北京");for (Person person : list) {
            System.out.println(person);
        }
    }

}

(6) 통합 테스트

Redis 클라이언트 시각적 관리 도구를 열고 먼저 로컬 Redis 서버에 연결합니다.

SpringBoot와 Redis를 통합하는 방법

연결에 성공한 후 로컬 Redis 데이터베이스에 데이터가 없는 것을 확인할 수 있습니다.

SpringBoot와 Redis를 통합하는 방법

A 테스트 메소드 위에 작성된 두 스크립트를 실행하고 콘솔 인쇄 결과를 확인하십시오.

SpringBoot와 Redis를 통합하는 방법

save() 메소드가 실제로 로컬 Redis 데이터베이스에 데이터를 썼는지 확인하려면 Redis 클라이언트 시각적 관리 도구를 엽니다. 데이터를 새로 고치면 데이터가 성공한 것을 확인할 수 있습니다. 작성:

SpringBoot와 Redis를 통합하는 방법

위 그림에서 볼 수 있듯이 save() 메소드를 실행하여 추가된 데이터가 Redis 데이터베이스에 성공적으로 저장되었습니다. 또한 데이터베이스 목록의 왼쪽에는 address.city, firstname, lastname 등과 유사한 보조 인덱스가 형성됩니다. 이러한 보조 인덱스는 Person 클래스 생성 시 해당 속성에 @Indexed 주석을 추가하여 생성됩니다. 동시에 해당 속성에 해당하는 보조 인덱스가 Redis 데이터베이스에 생성되므로 보조 인덱스를 통해 특정 데이터 정보를 쿼리할 수 있습니다. 예를 들어, repository.findByAddress_City("Beijing")는 인덱스 값이 베이징인 데이터를 쿼리합니다. address.city 인덱스 정보를 통해. 해당 속성의 보조 인덱스가 설정되지 않은 경우 속성 인덱스를 통해 쿼리한 데이터 결과는 비어 있게 됩니다.

위 내용은 SpringBoot와 Redis를 통합하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제