Spring Boot系列(七)Spring Boot使用Redis實現session共用
這一篇介紹Spring Boot使用Redis實現session共用,需要springboot實戰完整視頻教程的,點擊這裡。
Redis是一個緩衝訊息中介軟體及具有豐富特性的KVStore for Redis系統。Spring Boot為Jedis用戶端庫和由Spring Data Redis提供的基於Jedis用戶端的抽象提供自動設定。spring-boot-starter-redis'Starter POM'為收集依賴提供一種便利的方式。
引入spring-boot-starter-redis,在pom.xml設定檔中增加配置如下(基於之前章節“Spring Boot 構建架構”中的pom.xml檔案):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
可以注入一個自動設定的RedisConnectionFactory,StringRedisTemplate或普通的跟其他Spring Bean相同的RedisTemplate執行個體。預設情況下,這個執行個體將嘗試使用localhost:6379串連Redis伺服器。
@Component
public class MyBean {
private StringRedisTemplate template;
@Autowired
public MyBean(StringRedisTemplate template) {
this.template = template;
}
// ...
}
如果添加一個自己的任何自動設定類型的@Bean,它將替換預設的(除了RedisTemplate的情況,它是根據bean的名稱'redisTemplate'而不是它的類型進行排除的)。如果在classpath路徑下存在commons-pool2,預設會獲得一個串連池工廠。
應用使用Redis案例
添加設定檔,配置內容如下:
# REDIS (RedisProperties)
# Redis伺服器位址
spring.redis.host=192.168.0.58
# Redis伺服器串連連接埠
spring.redis.port=6379
# 連線逾時時間(毫秒)
spring.redis.timeout=0
redis配置類,具體代碼如下:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConn {
private String host;
private int port;
private int timeout;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
@Override
public String toString() {
return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]";
}
}
注意:在RedisConn類中註解@ConfigurationProperties(prefix = "spring.Redis")的作用是讀取springboot的預設設定檔資訊中以spring.redis開頭的資訊。
配置cache類
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;
import com.cachemodle.RedisConn;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @author sandsa redis cache service
*
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
private RedisConn redisConn;
/**
* 生產key的策略
*
* @return
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理緩衝
*
* @param redisTemplate
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager CacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 設定cache到期時間,時間單位是秒
rcm.setDefaultExpiration(60);
Map<String, Long> map = new HashMap<String, Long>();
map.put("test", 60L);
rcm.setExpires(map);
return rcm;
}
/**