一、整合Redis缓存
1、导入依赖
引入redis依赖包后系统就会自动引入RedisAutoConfiguration完成redis相关配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、编写Redis配置
#redis缓存
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.timeout=10000ms
3、模板编程及自定义CacheManager
实例项目使用 本文:https://mp.csdn.net/postedit/99118548
入口程序中添加@EnableCaching注解,开启缓存
(1)、模板编程controller
import com.example.bean.AnchorBaseInfoBean;
import com.example.dao.AnchorBaseInfoDao;
import com.example.service.AnchorBaseInfoService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value="/anchor", produces = "application/json; charset=UTF-8")
@Cacheable(cacheNames = {"test"}, cacheManager = "anchorBaseInfoCacheManager")
@Service
public class RedisCacheController {
@Autowired
private AnchorBaseInfoService anchorBaseInfoService;
@Autowired
private AnchorBaseInfoDao anchorBaseInfoDao;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate redisTemplate;
@Autowired
RedisTemplate empRedisTemplate; // 自定义RedisTemplate
// http://localhost:8080/anchor/getAnchorBaseInfoByPlatRoomCacheable?platID=2&roomID=1023513
@RequestMapping(value = "/getAnchorBaseInfoByPlatRoomCacheableRedis", method = {RequestMethod.GET})
// @Cacheable(value = "anchorinfo" ,key = "#p0 + #p1")
public AnchorBaseInfoBean getAnchorBaseInfoByPlatRoomCacheableRedis(
@ApiParam(value = "平台ID", required = true) @RequestParam(value = "platID", required = true) int platID,
@ApiParam(value = "房间ID", required = true) @RequestParam(value = "roomID", required = true) String roomID
) {
// 数据
AnchorBaseInfoBean resultBean=anchorBaseInfoDao.getAnchorBaseInfoByPlatRoom(platID,roomID);
System.out.println(resultBean.toString());
// 存储redis
// stringRedisTemplate.opsForList().leftPush("", "v1");
// stringRedisTemplate.opsForList().leftPush("list", "v2");
// stringRedisTemplate.opsForList().leftPush("list", "v3");
// stringRedisTemplate.opsForList().leftPush("list", "v4");
stringRedisTemplate.opsForValue().append("room_id",resultBean.getRoom_id() );
// 给redis存对象数据
// 这里使用默认的JDK序列化器:JdkSerializationRedisSerializer 将序列化后的数据保存到redis中
// 我们也可以自定义序列化器完成序列化存储
// 1. 自动手动将对象序列化为JSON字符串
// 2. 指定redisTemplate默认的序列化器
redisTemplate.opsForValue().set("plat_room", resultBean);
empRedisTemplate.opsForValue().set("plat_room_json", resultBean);
return resultBean;
}
}
(2)、自定义序列化器
新建config文件夹
import com.example.bean.AnchorBaseInfoBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, AnchorBaseInfoBean> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, AnchorBaseInfoBean> template = new RedisTemplate<Object, AnchorBaseInfoBean>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<AnchorBaseInfoBean> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(AnchorBaseInfoBean.class);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
}
(3)、自定义CacheManager(使用我们自己的序列化器)
使用Redis测试SpringBoot缓存原理:系统使用CacheManager(ConcurrentMapCacheManager默认)来创建Cache组件,来完成缓存的CRUD操作。
-
默认情况下系统使用SimpleCacheConfiguration来引入ConcurrentMapCacheManager缓存管理器–>ConcurrentMapCache作为缓存组件
-
引入了redis的starter后容器中保存的是RedisCacheManager–>RedisCache作为缓存组件(通过操作redis缓存数据), 默认保存数据 k-v 都是Object 默认利用jdk序列化保存
-
若使用自定义的序列化机制,则需要重写RedisCacheConfiguration类中的方法:
-
默认序列化方法为
@Bean
public RedisCacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setUsePrefix(true);
List cacheNames = this.cacheProperties.getCacheNames();
if(!cacheNames.isEmpty()) {
cacheManager.setCacheNames(cacheNames);
}
return (RedisCacheManager)this.customizerInvoker.customize(cacheManager);
}
自定义序列化方法,在config中新加CacheManager
package com.example.config;
import com.example.bean.AnchorBaseInfoBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
public class MyRedisCacheManager {
@Configuration
public class MyRedisConfig {
// AnchorBaseInfoBean
@Bean
public RedisTemplate<Object, AnchorBaseInfoBean> anchorBaseInfoRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, AnchorBaseInfoBean> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<AnchorBaseInfoBean> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(AnchorBaseInfoBean.class);
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public RedisCacheManager anchorBaseInfoCacheManager(RedisTemplate<Object, AnchorBaseInfoBean> empRedisTemplate) {
System.out.println(empRedisTemplate);
RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
// 使用前綴,默认使用cacheNames作为前缀
cacheManager.setUsePrefix(true);
return cacheManager;
}
//
// @Bean
// public RedisTemplate<Object, Department> deptRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
// RedisTemplate<Object, Department> template = new RedisTemplate<>();
// template.setConnectionFactory(redisConnectionFactory);
// Jackson2JsonRedisSerializer<Department> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Department.class);
// template.setDefaultSerializer(jackson2JsonRedisSerializer);
// return template;
// }
// @Bean
// public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate) {
// RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
// // 使用前綴,默认使用cacheNames作为前缀
// cacheManager.setUsePrefix(true);
// return cacheManager;
// }
@Primary
@Bean
public RedisCacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setUsePrefix(true);
return cacheManager;
}
}
}
(4)、使用自定义CacheManager
使用RedisCache时,若用自定义CacheManager,要使用注解指定CacheManager
@RestController
@RequestMapping(value="/anchor", produces = "application/json; charset=UTF-8")
@Cacheable(cacheNames = {"test"}, cacheManager = "anchorBaseInfoCacheManager")
@Service
public class RedisCacheController {
(5)、手动编码操作缓存
@Autowired
@Qualifier("empCacheManager")
CacheManager empCacheManager;
public Employee getEmp(Integer id){
Employee emp = employeeMapper.getEmpById(id);
// 获取某个缓存组件
Cache empCache = empCacheManager.getCache("emp");
empCache.put("emp:1", emp);
return emp;
}
(6)、实例测试
启动程序
http://localhost:8080/anchor/getAnchorBaseInfoByPlatRoomCacheableRedis?platID=2&roomID=1023513