整合Redis当然你要拥有一个Redis客户端,这个我就直接下载和配置了,没有的可以去下载一波
使用RedisTemplate
在SpringBoot中整合Redis很简单,只需要下面几个步骤
- 安装Redis(省略)
- 引入springdata-redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置redis
############################################REDIS的可选配置###################
#redis配置
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=3000
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=2
#连接超时时间(毫秒)
spring.redis.timeout=5000
- 注入RedisTemplate进行测试
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ShopApplicationTests {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate redisTemplate;
@Test
public void test01() {
stringRedisTemplate.opsForValue().set("k1", "v1");
}
@Test
public void test02(){
String k1 = stringRedisTemplate.opsForValue().get("k1");
log.info("拿到{}",v1);
}
}
- 自定义序列化器(如果不想使用JDK自带的序列化器)
我认为自定义序列化器有两种方法,第一种使用Spring配置一个特定的序列化器,第二种就是先将这个对象进行转化,然后将这个字符串存入Redis。
这里就以JSON序列为例,并且使用在Spring中配置序列化器
没有进行序列化设置默认采用JDK序列化
@Test
public void test03(){
User user = new User();
user.setId(1);
user.setName("张三");
redisTemplate.opsForValue().set("obj",user);
}@Test
public void test04(){
User obj = (User) redisTemplate.opsForValue().get("obj");
System.out.println(obj);
}
在Redis中显示如下
可以从Java自动反序列化拿到这个序列化的数据
虽然这样可以序列化对象,但是可读性太差,并且适用性不广泛,因此就让它转换一种序列化的形式
Redis序列化的原理
- 当我们导入starter时,会默认生成一个RedisCahceManager(不进行配置的话@MissingConfiguration)
- 然后RedisCacheManager帮我们创建RedisCahce来操作(通过使用RedisTemplate<Object,Object>)
- 然后RedisTemplate默认采用的是JDK序列化机制
因此我们就有思路怎样去配置Redis的序列化
package com.wrial.shop.config;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Slf4j
@Configuration
@EnableCaching//启用缓存,这个注解很重要;
//继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
public class CacheConfig extends CachingConfigurerSupport {
@Bean(name="redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<Object>(Object.class);
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(serializer);
template.setHashValueSerializer(serializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 生成一个默认配置,通过config对象即可对缓存进行自定义配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
// 设置缓存的默认过期时间,也是使用Duration设置
config = config.entryTtl(Duration.ofMinutes(1))
.disableCachingNullValues(); // 不缓存空值
// 设置一个初始化的缓存空间set集合
Set<String> cacheNames = new HashSet<>();
cacheNames.add("my-redis-cache1");
cacheNames.add("my-redis-cache2");
// 对每个缓存空间应用不同的配置
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("my-redis-cache1", config);
configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));
// 使用自定义的缓存配置初始化一个cacheManager
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.initialCacheNames(cacheNames) // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
.withInitialCacheConfigurations(configMap)
.build();
return cacheManager;
}
}
使用测试类进行测试
@Test
public void test05(){
User user = new User();
user.setId(5);
user.setName("王五");
redisTemplate.opsForValue().set("user1",user);
}
@Test
public void test06(){
Object user = redisTemplate.opsForValue().get("user");
User t = (User) JSON.toJavaObject((JSON) user, User.class);
System.out.println(t);
}