详解Spring Boot使用redis实现数据缓存
基于springBoot1.5.2.RELEASE版本,一方面验证与Redis的集成方法,另外了解使用方法。
集成方法
1、配置依赖
修改pom.xml,增加如下内容。
org.springframework.boot spring-boot-starter-data-redis
2、配置Redis
修改application.yml,增加如下内容。
spring: redis: host:localhost port:6379 pool: max-idle:8 min-idle:0 max-active:8 max-wait:-1
3、配置Redis缓存
packagenet.jackieathome.cache; importjava.lang.reflect.Method; importorg.springframework.cache.CacheManager; importorg.springframework.cache.annotation.CachingConfigurerSupport; importorg.springframework.cache.annotation.EnableCaching; importorg.springframework.cache.interceptor.KeyGenerator; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.data.redis.cache.RedisCacheManager; importorg.springframework.data.redis.connection.RedisConnectionFactory; importorg.springframework.data.redis.core.RedisTemplate; importorg.springframework.data.redis.core.StringRedisTemplate; importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; importcom.fasterxml.jackson.annotation.JsonAutoDetect; importcom.fasterxml.jackson.annotation.PropertyAccessor; importcom.fasterxml.jackson.databind.ObjectMapper; @Configuration @EnableCaching//启用缓存特性 publicclassRedisConfigextendsCachingConfigurerSupport{ //缓存数据时Key的生成器,可以依据业务和技术场景自行定制 //@Bean //publicKeyGeneratorcustomizedKeyGenerator(){ //returnnewKeyGenerator(){ //@Override //publicObjectgenerate(Objecttarget,Methodmethod,Object...params){ //StringBuildersb=newStringBuilder(); //sb.append(target.getClass().getName()); //sb.append(method.getName()); //for(Objectobj:params){ //sb.append(obj.toString()); //} //returnsb.toString(); //} //}; // //} //定制缓存管理器的属性,默认提供的CacheManager对象可能不能满足需要 //因此建议依赖业务和技术上的需求,自行做一些扩展和定制 @Bean publicCacheManagercacheManager(@SuppressWarnings("rawtypes")RedisTemplateredisTemplate){ RedisCacheManagerredisCacheManager=newRedisCacheManager(redisTemplate); redisCacheManager.setDefaultExpiration(300); returnredisCacheManager; } @Bean publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){ StringRedisTemplatetemplate=newStringRedisTemplate(factory); Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); returntemplate; } }
验证集成后的效果
考虑到未来参与的项目基于MyBatis实现数据库访问,而利用缓存,可有效改善Web页面的交互体验,因此设计了如下两个验证方案。
方案一
在访问数据库的数据对象上增加缓存注解,定义缓存策略。从测试效果看,缓存有效。
1、页面控制器
packagenet.jackieathome.controller; importjava.util.List; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.PathVariable; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RestController; importnet.jackieathome.bean.User; importnet.jackieathome.dao.UserDao; importnet.jackieathome.db.mapper.UserMapper; @RestController publicclassUserController{ @Autowired privateUserDaouserDao; @RequestMapping(method=RequestMethod.GET,value="/user/id/{id}") publicUserfindUserById(@PathVariable("id")Stringid){ returnuserDao.findUserById(id); } @RequestMapping(method=RequestMethod.GET,value="/user/create") publicUsercreateUser(){ longtime=System.currentTimeMillis()/1000; Stringid="id"+time; Useruser=newUser(); user.setId(id); userDao.createUser(user); returnuserDao.findUserById(id); } }
2、Mapper定义
packagenet.jackieathome.db.mapper; importjava.util.List; importorg.apache.ibatis.annotations.Mapper; importorg.apache.ibatis.annotations.Param; importorg.springframework.cache.annotation.CacheConfig; importorg.springframework.cache.annotation.CachePut; importorg.springframework.cache.annotation.Cacheable; importnet.jackieathome.bean.User; @Mapper publicinterfaceUserMapper{ voidcreateUser(Useruser); UserfindUserById(@Param("id")Stringid); }
3、数据访问对象
packagenet.jackieathome.dao; importjava.util.ArrayList; importjava.util.List; importorg.apache.ibatis.annotations.Param; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.cache.annotation.CacheConfig; importorg.springframework.cache.annotation.CachePut; importorg.springframework.cache.annotation.Cacheable; importorg.springframework.stereotype.Component; importorg.springframework.transaction.annotation.Transactional; importnet.jackieathome.bean.User; importnet.jackieathome.db.mapper.UserMapper; @Component @CacheConfig(cacheNames="users") @Transactional publicclassUserDao{ privatestaticfinalLoggerLOG=LoggerFactory.getLogger(UserDao.class); @Autowired privateUserMapperuserMapper; @CachePut(key="#p0.id") publicvoidcreateUser(Useruser){ userMapper.createUser(user); LOG.debug("createuser="+user); } @Cacheable(key="#p0") publicUserfindUserById(@Param("id")Stringid){ LOG.debug("finduser="+id); returnuserMapper.findUserById(id); } }
方案二
直接在Mapper定义上增加缓存注解,控制缓存策略。从测试效果看,缓存有效,相比于方案一,测试代码更加简洁一些。
1、页面控制器
packagenet.jackieathome.controller; importjava.util.List; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.PathVariable; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RestController; importnet.jackieathome.bean.User; importnet.jackieathome.dao.UserDao; importnet.jackieathome.db.mapper.UserMapper; @RestController publicclassUserController{ @Autowired privateUserMapperuserMapper; @RequestMapping(method=RequestMethod.GET,value="/user/id/{id}") publicUserfindUserById(@PathVariable("id")Stringid){ returnuserMapper.findUserById(id); } @RequestMapping(method=RequestMethod.GET,value="/user/create") publicUsercreateUser(){ longtime=System.currentTimeMillis()/1000; Stringid="id"+time; Useruser=newUser(); user.setId(id); userMapper.createUser(user); returnuserMapper.findUserById(id); } }
2、Mapper定义
packagenet.jackieathome.db.mapper; importjava.util.List; importorg.apache.ibatis.annotations.Mapper; importorg.apache.ibatis.annotations.Param; importorg.springframework.cache.annotation.CacheConfig; importorg.springframework.cache.annotation.CachePut; importorg.springframework.cache.annotation.Cacheable; importnet.jackieathome.bean.User; @CacheConfig(cacheNames="users") @Mapper publicinterfaceUserMapper{ @CachePut(key="#p0.id") voidcreateUser(Useruser); @Cacheable(key="#p0") UserfindUserById(@Param("id")Stringid); }
总结
上述两个测试方案并没有优劣之分,仅是为了验证缓存的使用方法,体现了不同的控制粒度,在实际的项目开发过程中,需要依据实际情况做不同的决断。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。