springboot整合Redis詳解
阿新 • • 發佈:2020-12-12
我們現在專案大都使用springboot,那如何在springboot中加入redis呢?
主要有以下這幾步:
1.需要加入Redis的依賴Jar,程式碼為:
<! -redis依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${spring-boot.version}</version> </dependency>
2.只需要在配置檔案application.properties中加入Redis的連線配置即可
# Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 spring.redis.host=192.168.0.24 # Redis伺服器連線埠 spring.redis.port=6379 # Redis伺服器連線密碼(預設為空) spring.redis.password= # 連線池最大連線數(使用負值表示沒有限制) spring.redis.pool.max-active=200 # 連線池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.pool.max-wait=-1 # 連線池中的最大空閒連線 spring.redis.pool.max-idle=10 # 連線池中的最小空閒連線 spring.redis.pool.min-idle=0 # 連線超時時間(毫秒) spring.redis.timeout=1000
3.Redis自定義注入bean元件配置
對於Spring Boot專案整合Redis,最主要的Bean操作元件莫過於RedisTemplate跟StringRedisTemplate,後者其實是前者的一種特殊體現。而在專案中使用Redis的過程中,一般情況下是需要自定義配置上述兩個操作Bean元件的,比如指定快取中Key與Value的序列化策略等配置。以下程式碼為自定義注入配置操作元件RedisTemplate與StringRedis-Template相關屬性:
package com.coding.fight.server.config; //匯入包 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.JdkSerializationRedis Serializer; import org.springframework.data.redis.serializer.StringRedisSerializer; //通用化配置 @Configuration public class CommonConfig { //Redis連結工廠 @Autowired private RedisConnectionFactory redisConnectionFactory; //快取操作元件RedisTemplate的自定義配置 @Bean public RedisTemplate<String, Object> redisTemplate(){ //定義RedisTemplate例項 RedisTemplate<String, Object> redisTemplate=new RedisTemplate <String, Object>(); //設定Redis的連結工廠 redisTemplate.setConnectionFactory(redisConnectionFactory); //TODO:指定大Key序列化策略為String序列化,Value為JDK自帶的序列化策略 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); //TODO:指定hashKey序列化策略為String序列化-針對hash雜湊儲存 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); return redisTemplate; } //快取操作元件StringRedisTemplate @Bean public StringRedisTemplate stringRedisTemplate(){ //採用預設配置即可-後續有自定義配置時則在此處新增即可 StringRedisTemplate stringRedisTemplate=new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(redisConnectionFactory); return stringRedisTemplate; } }
上述程式碼中對於RedisTemplate自定義注入配置的屬性主要是快取中Key與Value的序列化策略;對於StringRedisTemplate則採用預設的配置,後續如果有自定義的配置時則可以在此處新增。
4.1RedisTemplate實戰**
演示RedisTemplate操作元件的應用
- 採用RedisTemplate將字串資訊寫入快取中,並讀取出來展示到控制檯上。
- 採用RedisTemplate將物件資訊序列化為JSON格式的字串後寫入快取中,然後將其讀取出來,最後反序列化解析其中的內容並展示在控制檯上。
//1.
package com.debug.middleware.server;
//匯入包
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//單元測試類
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
//定義日誌
private static final Logger log= LoggerFactory.getLogger(RedisTest.
class);
//由於之前已經自定義注入RedisTemplate元件,因而在此可以直接自動裝配
@Autowired
private RedisTemplate redisTemplate;
//採用RedisTemplate將字串資訊寫入快取中並讀取出來
@Test
public void one(){
log.info("------開始RedisTemplate操作元件實戰----");
//定義字串內容及存入快取的key
final String content="RedisTemplate實戰字串資訊";
final String key="redis:template:one:string";
//Redis通用的操作元件
ValueOperations valueOperations=redisTemplate.opsForValue();
//將字串資訊寫入快取中
log.info("寫入快取中的內容:{} ", content);
valueOperations.set(key, content);
//從快取中讀取內容
Object result=valueOperations.get(key);
log.info("讀取出來的內容:{} ", result);
}
}
2.
package com.debug.middleware.server;
//匯入包
import com.debug.middleware.server.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//單元測試類
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
//定義日誌
private static final Logger log= LoggerFactory.getLogger(RedisTest.class);
//定義RedisTemplate操作元件
@Autowired
private RedisTemplate redisTemplate;
//定義JSON序列化與反序列化框架類
@Autowired
private ObjectMapper objectMapper;
//採用RedisTemplate將物件資訊序列化為JSON格式字串後寫入快取中
//然後將其讀取出來,最後反序列化解析其中的內容並展示在控制檯上
@Test
public void two() throws Exception{
log.info("------開始RedisTemplate操作元件實戰----");
//構造物件資訊
User user=new User(1, "debug", "阿修羅");
//Redis通用的操作元件
ValueOperations valueOperations=redisTemplate.opsForValue();
//將序列化後的資訊寫入快取中
final String key="redis:template:two:object";
final String content=objectMapper.writeValueAsString(user);
valueOperations.set(key, content);
log.info("寫入快取物件的資訊:{} ", user);
//從快取中讀取內容
Object result=valueOperations.get(key);
if (result! =null){
User resultUser=objectMapper.readValue(result.toString(), User.class);
log.info("讀取快取內容並反序列化後的結果:{} ", resultUser);
}
}
4.2StringRedisTemplate實戰
StringRedisTemplate用於操作字串型別的資料資訊。
/定義StringRedisTemplate操作元件
@Autowired
private StringRedisTemplate stringRedisTemplate;
//採用StringRedisTemplate將字串資訊寫入快取中並讀取出來
@Test
public void three(){
log.info("------開始StringRedisTemplate操作元件實戰----");
//定義字串內容及存入快取的key
final String content="StringRedisTemplate實戰字串資訊";
final String key="redis:three";
//Redis通用的操作元件
ValueOperations valueOperations=stringRedisTemplate.opsForValue();
//將字串資訊寫入快取中
log.info("寫入快取中的內容:{} ", content);
valueOperations.set(key, content);
//從快取中讀取內容
Object result=valueOperations.get(key);
log.info("讀取出來的內容:{} ", result);
}
//採用StringRedisTemplate將物件資訊序列化為JSON格式字串後寫入快取中
//然後將其讀取出來,最後反序列化解析其中的內容並展示在控制檯上
@Test
public void four() throws Exception{
log.info("------開始StringRedisTemplate操作元件實戰----");
//構造物件資訊
User user=new User(2, "SteadyJack", "阿修羅");
//Redis通用的操作元件
ValueOperations valueOperations=redisTemplate.opsForValue();
//將序列化後的資訊寫入快取中
final String key="redis:four";
final String content=objectMapper.writeValueAsString(user);
valueOperations.set(key, content);
log.info("寫入快取物件的資訊:{} ", user);
//從快取中讀取內容
Object result=valueOperations.get(key);
if (result! =null){
User resultUser=objectMapper.readValue(result.toString(), User.class);
log.info("讀取快取內容並反序列化後的結果:{} ", resultUser);
}
}