前言

除了對關係型資料庫的整合支援外,SpringBoot對非關係型資料庫也提供了非常好的支援,比如,對Redis的支援。

Redis(Remote Dictionary Server,即遠端字典服務)是一個高效能的key-value資料庫,它是一種跨平臺的非關係型資料庫。Redis 通常被稱為資料結構伺服器,因為它的值(value)可以是字串(String)、雜湊(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等型別。

下面,我們來看一下SpringBoot與Redis要如何進行整合。

SpringBoot與非關係型資料庫Redis的整合

(1)新增Spring Data Redis依賴啟動器

引入這個依賴器建立專案,在專案pom.xml檔案會出現以下依賴:

(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; @Indexed
private 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;
} @Override
public 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 { @Indexed
private String city; @Indexed
private 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;
} @Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
}

在上述兩個實體類中,涉及了關於Redis資料庫的資料操作的幾個註解:

  • @RedisHash("persons"):用於指定操作實體類物件在Redis資料庫中的儲存空間,此處表示針對Person實體類的資料操作都儲存在Redis資料庫中名為persons的儲存空間下。
  • @Id:用於標識實體類主鍵。在Redis資料庫中會預設生成字串形式的HashKey表示唯一的實體物件id,當然也可以在資料儲存時手動指定id。
  • @Indexed:用於標識對應屬性在Redis資料庫中生成二級索引。使用該註解後會在資料庫中生成屬性對應的二級索引,索引名稱就是屬性名,可以方便地進行資料查詢。

(3)編寫Repository介面

SpringBoot針對包括Redis在內的一些常用資料庫提供了自動化配置,可以通過實現Repository介面簡化對資料庫中的資料進行增刪查改的操作:

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介面類需要繼承最底層的CrudRepository介面,而不是繼承JpaRepository(JpaRepository是SpringBoot整合JPA特有的)。當然,也可以在專案pom.xml檔案中同時匯入SpringBoot整合的JPA依賴和Redis依賴,這樣就可以編寫一個繼承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; @SpringBootTest
class SpringbootdataRedisApplicationTests { @Autowired
private PersonRepository repository; @Test
public 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);
} @Test
public void selectPerson() {
List<Person> list = repository.findByAddress_City("北京");
for (Person person : list) {
System.out.println(person);
}
} }

(6)整合測試

開啟Redis客戶端視覺化管理工具,先連線本地Redis伺服器:

連線成功後,可以看到原來本地Redis資料庫中是沒有資料的:

執行上文中編寫好的兩個測試方法,檢視控制檯列印結果:

為了驗證save()方法確實把資料寫入到本地Redis資料庫中了,開啟Redis客戶端視覺化管理工具,重新整理一下資料,可以看到資料成功寫入了:

通過上圖可知:執行save()方法新增的資料在Redis資料庫中儲存成功。另外,在資料庫列表左側還形成了一張類似address.city、firstname、lastname等二級索引,這些二級索引是前面建立Person類時在對應屬性上新增@Indexed註解而生成的。同時,由於在Redis資料庫中生成了對應屬性的二級索引,所以可以通過二級索引來查詢具體的資料資訊,例如repository.findByAddress_City("北京")通過address.city索引查詢索引值為北京的資料資訊。如果沒有設定對應屬性的二級索引,那麼通過屬性索引查詢的資料結果將為空。