Springboot|Springboot 利用redis 作二级缓存

一、导入redis jar包

org.springframework.boot spring-boot-starter-data-redis redis.clients jedis 2.9.0

启动类加上 @EnableCaching注解表示开启缓存功能
@SpringBootApplication //开启缓存功能 @EnableCaching public class ShiroApplication {public static void main(String[] args) { SpringApplication.run(ShiroApplication.class, args); }}


二、redis配置
#redis配置# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.jedis.pool.max-idle=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.jedis.pool.max-wait=-1 # 连接池中的最小空闲连接 spring.redis.jedis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=10000

三、Redis缓存配置类
package com.example.springboot.shiro.core.shiro; 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.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; 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.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.lang.reflect.Method; import java.time.Duration; /** * Redis缓存配置类 * * @author szekinwin */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport {@Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; //缓存管理器 @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); }@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory factory) {RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(factory); //key序列化方式; (不然会出现乱码; ),但是如果方法上有Long等非String类型的话,会报类型转换错误;//所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer//或者JdkSerializationRedisSerializer序列化方式; RedisSerializer redisSerializer = new StringRedisSerializer(); //Long类型不可以会出现异常信息; redisTemplate.setKeySerializer(redisSerializer); redisTemplate.setHashKeySerializer(redisSerializer); //设置序列化Value的实例化对象 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } /*** 自定义key.* 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。*/public KeyGenerator keyGenerator() {System.out.println("RedisCacheConfig.keyGenerator()"); return new KeyGenerator(){@Overridepublic Object generate(Object o, Method method, Object... objects) {// This willgenerate a unique key of the class name, the method name//and allmethod parameters appended.StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) {sb.append(obj.toString()); }System.err.print("keyGenerator======>>>>>>" + sb.toString()); return sb.toString(); }}; } }

注: 如果报类型转换异常,请把热部署or 热加载关闭
四、redisMapper
package com.example.springboot.shiro.user.mapper; import com.example.springboot.shiro.user.entity.Uuser; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; /* * @Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key。 * @CachePut,指定key,将更新的结果同步到redis中 * @CacheEvict,指定key,删除缓存数据,allEntries=true,方法调用后将立即清除缓存 */@Mapper @CacheConfig(cacheNames = "Uuser") public interface RedisMapper { @CachePut(value = "https://www.it610.com/article/usercache", key = "#p0") @Insert("insert into u_user(email,pswd) values(#{email},#{pswd})") int addUser(@Param("email")String email,@Param("pswd")String pswd); @Select("select * from u_user where email=#{email}")Uuser findById(@Param("email") String email); @CachePut(key = "#p0") @Update("update u_user set email=#{email} where id=#{id}") void updataById(@Param("id")String id,@Param("email")String email); //如果指定为 true,则方法调用后将立即清空所有缓存 @CacheEvict(key ="#p0",allEntries=true) @Delete("delete from u_user where id=#{id}") int deleteById(@Param("id")int id); }

注:关于缓存注解也可以标注在Service 类上,两者取其一
@Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key @CachePut,指定key,将更新的结果同步到redis中 @CacheEvict,指定key,删除缓存数据,allEntries=true(方法调用后将立即清除所有缓存), @CacheConfig(cacheNames = "Uuser")表示缓存信息放在Uuser里面

【Springboot|Springboot 利用redis 作二级缓存】五、Service
@Cacheable(value = "https://www.it610.com/article/demoInfo") //缓存,这里没有指定key. public Uuser findById(String email) { System.err.println("LoginService.findById()=========从数据库中进行获取的....email=" + email); return redisMapper.findById(email); }@CacheEvict(value = "https://www.it610.com/article/demoInfo") public void deleteFromCache(String email) {System.err.println("LoginService.delete().从缓存中删除."); }

注:@Cacheable(value ="https://www.it610.com/article/demoInfo") 表示 缓存信息放在demoInfo里面
@CacheEvict(value="https://www.it610.com/article/demoInfo") 表示清除demoInfo里面的缓存里面的信息
六、Controller
@RequestMapping(value = "https://www.it610.com/article/redis",method = RequestMethod.POST) @ResponseBody public Uuser findById(String email) {return loginService.findById(email); } @RequestMapping(value = "https://www.it610.com/article/delete",method = RequestMethod.POST) @ResponseBody public String delete(String email){ loginService.deleteFromCache(email); return "ok"; }

七、测试
第一次:执行findById()方法
keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadmin2018-07-29 15:31:19.165INFO 10404 --- [nio-8080-exec-1] io.lettuce.core.EpollProvider: Starting without optional epoll library 2018-07-29 15:31:19.165INFO 10404 --- [nio-8080-exec-1] io.lettuce.core.KqueueProvider: Starting without optional kqueue library keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadminLoginService.findById()=========从数据库中进行获取的....email=admin 2018-07-29 15:31:20,257 DEBUG DataSourceUtils:114 - Fetching JDBC Connection from DataSource

从上图可以看出,数据第一次是从数据库拿出,此时redis 缓存已生成,自定义key已生成
再次执行:执行findById()方法
keyGenerator======>>>>>>com.example.springboot.shiro.user.service.LoginServicefindByIdadmin2018-07-29 15:40:47,598 DEBUG RequestResponseBodyMethodProcessor:278 - Written [{"create_time":{"date":16,"day":4,"hours":11,"minutes":15,"month":5,"seconds":33,"time":1466046933000,"timezoneOffset":-480,"year":116},"email":"admin","id":1,"last_login_time":{"date":29,"day":0,"hours":12,"minutes":55,"month":6,"seconds":4,"time":1532840104000,"timezoneOffset":-480,"year":118},"nickname":"???","pswd":"","salt":"","status":1,"verificationCode":""}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@987455b] 2018-07-29 15:40:47,599 DEBUG DispatcherServlet:1076 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling 2018-07-29 15:40:47,599 DEBUG DispatcherServlet:1000 - Successfully completed request

从日志中不难看出,第二次查询并没有到数据库中去查询,而是去缓存中调用。
转载于:https://www.cnblogs.com/wang-qiang/p/9432275.html

    推荐阅读