博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot整合redis进行数据缓存
阅读量:4979 次
发布时间:2019-06-12

本文共 9559 字,大约阅读时间需要 31 分钟。

一、添加redis依赖:

   

1 
2
3
org.springframework.boot
4
spring-boot-starter-data-redis
5

二、redis配置文件:

1 #redis2 spring.redis.host= localhost3 spring.redis.port= 63794 spring.redis.password= 123456   //如果redis没有设置密码,则可以注释本行5 spring.redis.pool.max-idle= 86 spring.redis.pool.min-idle= 07 spring.redis.pool.max-active= 88 spring.redis.pool.max-wait= -19 spring.redis.timeout= 0

三、新建redis配置类:

1 package main.config; 2  3 import java.lang.reflect.Method; 4  5 import org.springframework.cache.CacheManager; 6 import org.springframework.cache.annotation.CachingConfigurerSupport; 7 import org.springframework.cache.annotation.EnableCaching; 8 import org.springframework.cache.interceptor.KeyGenerator; 9 import org.springframework.context.annotation.Bean;10 import org.springframework.context.annotation.Configuration;11 import org.springframework.data.redis.cache.RedisCacheManager;12 import org.springframework.data.redis.connection.RedisConnectionFactory;13 import org.springframework.data.redis.core.RedisTemplate;14 import org.springframework.data.redis.core.StringRedisTemplate;15 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;16 import com.fasterxml.jackson.annotation.JsonAutoDetect;17 import com.fasterxml.jackson.annotation.PropertyAccessor;18 import com.fasterxml.jackson.databind.ObjectMapper;19 20 /**21  * redis 缓存配置;22  *23  * 注意:RedisCacheConfig这里也可以不用继承:CachingConfigurerSupport,也就是直接一个普通的Class就好了;24  *25  * 这里主要我们之后要重新实现 key的生成策略,只要这里修改KeyGenerator,其它位置不用修改就生效了。26  *27  * 普通使用普通类的方式的话,那么在使用@Cacheable的时候还需要指定KeyGenerator的名称;这样编码的时候比较麻烦。28  *29  * 30  * @version v.0.131  */32 @Configuration33 @EnableCaching // 启用缓存,这个注解很重要;34 public class RedisCacheConfig extends CachingConfigurerSupport {35     /**36      * 缓存管理器.37      * 38      * @param redisTemplate39      * @return40      */41     @Bean42     public CacheManager cacheManager(RedisTemplate
redisTemplate) {43 CacheManager cacheManager = new RedisCacheManager(redisTemplate);44 return cacheManager;45 }46 47 /**48 * RedisTemplate缓存操作类,类似于jdbcTemplate的一个类;49 * 虽然CacheManager也能获取到Cache对象,但是操作起来没有那么灵活;50 * 这里在扩展下:RedisTemplate这个类不见得很好操作,我们可以在进行扩展一个我们51 * 自己的缓存类,比如:RedisStorage类;52 * @param factory53 * : 通过Spring进行注入,参数在application.properties进行配置;54 * @return55 */56 @Bean57 public RedisTemplate
redisTemplate(RedisConnectionFactory factory) {58 StringRedisTemplate template = new StringRedisTemplate(factory); 59 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 60 ObjectMapper om = new ObjectMapper(); 61 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 62 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 63 jackson2JsonRedisSerializer.setObjectMapper(om); 64 template.setValueSerializer(jackson2JsonRedisSerializer); 65 template.afterPropertiesSet(); 66 return template; 67 }68 /**69 * 注入自定义key的格式70 * @return71 */72 @Bean73 public KeyGenerator wiselyKeyGenerator(){74 return keyGenerator();75 }76 /**77 * 自定义key. 此方法将会根据类名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。 ps:一般情况使用类+方法+所有参数,,,由于本例子会介绍到清楚缓存,所以自定义key为类+所有参数78 */79 @Override80 public KeyGenerator keyGenerator() {81 System.out.println("RedisCacheConfig.keyGenerator()");82 return new KeyGenerator() {83 @Override84 public Object generate(Object o, Method method, Object... objects) {85 StringBuilder sb = new StringBuilder();86 sb.append(o.getClass().getName());87 //sb.append(method.getName());88 for (Object obj : objects) {89 sb.append(obj.toString());90 }91 System.out.println("keyGenerator=" + sb.toString());92 return sb.toString();93 }94 };95 }96 }

四、编写测试类Raddress,RuserInfo:

1 package main.entity; 2  3 public class Raddress { 4     private Long id; 5     private String province; 6     private String city; 7  8     public Raddress(Long id, String province, String city) { 9         this.id = id;10         this.province = province;11         this.city = city;12     }13 14     public Raddress() {15     }16 17     public Long getId() {18         return id;19     }20 21     public void setId(Long id) {22         this.id = id;23     }24 25     public String getProvince() {26         return province;27     }28 29     public void setProvince(String province) {30         this.province = province;31     }32 33     public String getCity() {34         return city;35     }36 37     public void setCity(String city) {38         this.city = city;39     }40     @Override41     public String toString(){42         return "Raddress: [id="+this.id+",province="+this.province+",city="+this.city+"]";43     }44 }
1 package main.entity; 2  3 public class RuserInfo { 4     private Long id; 5     private String firstName; 6     private String lastName; 7  8     public RuserInfo(Long id, String firstName, String lastName) { 9         this.id = id;10         this.firstName = firstName;11         this.lastName = lastName;12     }13 14     public RuserInfo() {15     }16 17     public Long getId() {18         return id;19     }20 21     public void setId(Long id) {22         this.id = id;23     }24 25     public String getFirstName() {26         return firstName;27     }28 29     public void setFirstName(String firstName) {30         this.firstName = firstName;31     }32 33     public String getLastName() {34         return lastName;35     }36 37     public void setLastName(String lastName) {38         this.lastName = lastName;39     }40     @Override41     public String toString(){42         return "RuserInfo: [id="+this.id+",firstName="+this.firstName+",lastName="+this.lastName+"]";43     }44 }
1 package main.dao; 2  3 import org.springframework.cache.annotation.CacheEvict; 4 import org.springframework.cache.annotation.Cacheable; 5 import org.springframework.stereotype.Repository; 6  7 import main.entity.Raddress; 8 import main.entity.RuserInfo; 9 /**10  * Redis Cache Test Class11  * @author wangyao12  *13  */14 @Repository15 public class RCacheDemoDao {16     17     /**18      * 使用自定义key(类名+方法名+所有参数)19      * 也可以直接使用cacheable的参数key :  ,key="#userId + 'findById'20      * @param id21      * @param firstName22      * @param lastName23      * @return24      */25     @Cacheable(value="addUserCache",keyGenerator="wiselyKeyGenerator")26     public RuserInfo findUserById(Long id, String firstName, String lastName){27         System.out.println("//将缓存保存进andUserCache");28         return new RuserInfo(id, firstName, lastName);29     }30     @Cacheable(value="addAddressCache",keyGenerator="wiselyKeyGenerator")31     public Raddress findAddressById(Long id, String province, String city){32         System.out.println("//将缓存保存进addAddressCache");33         return new Raddress(id, province, city);34     }35    //CacheEvict清除缓存,默认为false,清除addUserCache下的key为wiselyKeyGenerator格式的缓存
36     @CacheEvict(value="addUserCache",keyGenerator="wiselyKeyGenerator")
37     public void deleteUserById(Long id, String firstName, String lastName) { 38         System.out.println("//从缓存中删除.addUserCache"); 39     } 40     @CacheEvict(value="addUserCache",allEntries=true) //CacheEvict清除缓存,默认为false,清除addUserCache下的所有缓存 41     public void deleteUserAll() { 42         System.out.println("//从缓存中删除所有.addUserCache"); 43     } 44 }

五、新建测试controller:

  

1 package main.controller; 2  3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.GetMapping; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 import org.springframework.web.bind.annotation.RestController; 8  9 import main.config.Test2Config;10 import main.config.TestConfig;11 import main.dao.RCacheDemoDao;12 import main.entity.Raddress;13 import main.entity.RuserInfo;14 15 @RestController16 public class RCacheDemoController {17     @Autowired18     RCacheDemoDao rCacheDemoDao;19     @Autowired20     TestConfig testConfig;21     @Autowired22     Test2Config test2Config;23     @GetMapping("/test")24     public String putCache() {25         rCacheDemoDao.findUserById(1L, "王", "尧");26         rCacheDemoDao.findAddressById(1L, "上海", "虹口");27         System.out.println("是否有缓存对象存在,如有则不会打印://存入缓存至xx中");28         return "test";29     }30 31     @GetMapping("/destroy")32     public String destroyCache() {33         rCacheDemoDao.deleteUserById(1L, "王", "尧");34         return "destroy";35     }36 37     @GetMapping("/destroyAll")38     public String destroyAllCache() {39         rCacheDemoDao.deleteUserAll();40         return "destroyAll";41     }42 43     @GetMapping("/test2")44     public String testCache() {45         RuserInfo user = rCacheDemoDao.findUserById(1L, "王", "尧");46         Raddress address = rCacheDemoDao.findAddressById(1L, "上海", "虹口");47         System.out.println(user.toString());48         System.out.println(address.toString());49         return "test";50     }51 }

六、相关工具:

redis:

redis管理工具:

 

 下载地址:https://pan.baidu.com/s/1qYgC51E

转载于:https://www.cnblogs.com/wangyaobk/articles/7472932.html

你可能感兴趣的文章
Contest Record
查看>>
51Nod 1066 - Bash游戏
查看>>
oracle控制何时触发审计动作
查看>>
NVelocity用法
查看>>
关于xp_cmdshall开启特定账号执行的相关设置步骤
查看>>
[USACO 6.3.2] Cryptcowgraphy
查看>>
.net 开发人员面试题 - 多线程
查看>>
PHP实现的快速排序
查看>>
Dave Python 练习十七 -- 正则表达式
查看>>
混沌开窍---24幅由算法生成的正方形图像
查看>>
java中newInstance和new(转)
查看>>
面向对象技术
查看>>
centos7 Linux 安装mysql
查看>>
dom的综合练习
查看>>
python中sort方法
查看>>
python字符串
查看>>
pb设计笔记
查看>>
ADO.NET中调用存储过程
查看>>
开发者 发展 2 码路指南
查看>>
830. Positions of Large Groups
查看>>