原文:http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html

https://blog.csdn.net/plei_yue/article/details/79362372

jar包版本:

jedis-2.9.0.jar

commons-pool2-2.4.3.jar

spring-*-3.24.jar

如何使用

1、引入 spring-boot-starter-redis

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-redis</artifactId>
  4. </dependency>

2、添加配置文件

  1. # REDIS (RedisProperties)
  2. # Redis数据库索引(默认为0)
  3. spring.redis.database=0
  4. # Redis服务器地址
  5. spring.redis.host=192.168.0.58
  6. # Redis服务器连接端口
  7. spring.redis.port=6379
  8. # Redis服务器连接密码(默认为空)
  9. spring.redis.password=
  10. # 连接池最大连接数(使用负值表示没有限制)
  11. spring.redis.pool.max-active=8
  12. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  13. spring.redis.pool.max-wait=-1
  14. # 连接池中的最大空闲连接
  15. spring.redis.pool.max-idle=8
  16. # 连接池中的最小空闲连接
  17. spring.redis.pool.min-idle=0
  18. # 连接超时时间(毫秒)
  19. spring.redis.timeout=0

3、添加cache的配置类

  StringRedisTemplate默认采用的key序列化方式为setKeySerializer(stringSerializer);此时在使用Spring的缓存注解如@Cacheable的key属性设置值时,就需

要注意如果参数类型为Long那么会出不能进行String类型转换异常。
      RedisTemplate默认使用的序列化方式为JdkSerializationRedisSerializer,它就没有上边的问题。因为它的序列化方法为serialize(Object object)

  1. @Configuration
  2. @EnableCaching
  3. public class RedisConfig extends CachingConfigurerSupport{
  4. @Bean
  5. public KeyGenerator keyGenerator() {
  6. return new KeyGenerator() {
  7. @Override
  8. public Object generate(Object target, Method method, Object... params) {
  9. StringBuilder sb = new StringBuilder();
  10. sb.append(target.getClass().getName());
  11. sb.append(method.getName());
  12. for (Object obj : params) {
  13. sb.append(obj.toString());
  14. }
  15. return sb.toString();
  16. }
  17. };
  18. }
  19. @SuppressWarnings("rawtypes")
  20. @Bean
  21. public CacheManager cacheManager(RedisTemplate redisTemplate) {
  22. RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
  23. //设置缓存过期时间
  24. //rcm.setDefaultExpiration(60);//秒
  25. return rcm;
  26. }
  27. @Bean
  28. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  29. StringRedisTemplate template = new StringRedisTemplate(factory);
  30. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  31. ObjectMapper om = new ObjectMapper();
  32. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  33. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  34. jackson2JsonRedisSerializer.setObjectMapper(om);
  35. template.setValueSerializer(jackson2JsonRedisSerializer);
  36. template.afterPropertiesSet();
  37. return template;
  38. }
  39. }

  40. 如果你只需要使用基本的redis配置,那么使用如下配置类即可,spring boot会自动扫描redis的基本配置,但是有一项要注意那就是password,如果你在配置文件中设置了password,那么就必须在配置类中手工注入JedisConnectionFactory中,否则会在启动过程中报NOAUTH Authentication required.;:
  1. @Bean
  2. public JedisConnectionFactory redisConnectionFactory() {
  3. JedisConnectionFactory factory = new JedisConnectionFactory();
  4. factory.setHostName(host);
  5. factory.setPort(port);
  6. factory.setPassword(password);
  7. factory.setTimeout(timeout); //设置连接超时时间
  8.  
  9. //连接池配置
  10. JedisPoolConfig poolConfig = new JedisPoolConfig();
  11. poolConfig.setMinIdle(minIdle);
  12. poolConfig.setMaxIdle(maxIdle);
  13. poolConfig.setMaxTotal(maxTotal);
  14. poolConfig.setMaxWaitMillis(maxWait);
  15.  
  16. factory.setPoolConfig(poolConfig);
  17. return factory;
  18. }
  1. JedisPoolConfig config = new JedisPoolConfig();
  2.  
  3. //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
  4. config.setBlockWhenExhausted(true);
  5.  
  6. //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
  7. config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
  8.  
  9. //是否启用pool的jmx管理功能, 默认true
  10. config.setJmxEnabled(true);
  11.  
  12. //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
  13. config.setJmxNamePrefix("pool");
  14.  
  15. //是否启用后进先出, 默认true
  16. config.setLifo(true);
  17.  
  18. //最大空闲连接数, 默认8个
  19. config.setMaxIdle(8);
  20.  
  21. //最大连接数, 默认8个
  22. config.setMaxTotal(8);
  23.  
  24. //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
  25. config.setMaxWaitMillis(-1);
  26.  
  27. //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
  28. config.setMinEvictableIdleTimeMillis(1800000);
  29.  
  30. //最小空闲连接数, 默认0
  31. config.setMinIdle(0);
  32.  
  33. //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
  34. config.setNumTestsPerEvictionRun(3);
  35.  
  36. //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略)
  37. config.setSoftMinEvictableIdleTimeMillis(1800000);
  38.  
  39. //在获取连接的时候检查有效性, 默认false
  40. config.setTestOnBorrow(false);
  41.  
  42. //在空闲时检查有效性, 默认false
  43. config.setTestWhileIdle(false);
  44.  
  45. //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
  46. config.setTimeBetweenEvictionRunsMillis(-1);

3、好了,接下来就可以直接使用了,测试

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringApplicationConfiguration(Application.class)
  3. public class TestRedis {
  4. @Autowired
  5. private StringRedisTemplate stringRedisTemplate;
  6. @Autowired
  7. private RedisTemplate redisTemplate;
  8. @Test
  9. public void test() throws Exception {
  10. stringRedisTemplate.opsForValue().set("aaa", "111");
  11. Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
  12. }
  13. @Test
  14. public void testObj() throws Exception {
  15. User user=new User("aa@126.com", "aa", "aa123456", "aa","123");
  16. ValueOperations<String, User> operations=redisTemplate.opsForValue();
  17. operations.set("com.neox", user);
  18. operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
  19. Thread.sleep(1000);
  20. //redisTemplate.delete("com.neo.f");
  21. boolean exists=redisTemplate.hasKey("com.neo.f");
  22. if(exists){
  23. System.out.println("exists is true");
  24. }else{
  25. System.out.println("exists is false");
  26. }
  27. // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
  28. }
  29. }

以上都是手动使用的方式,如何在查找数据库的时候自动使用缓存呢,看下面;

4、自动根据方法生成缓存

  1. @RequestMapping("/getUser")
  2. @Cacheable(value="user-key")
  3. public User getUser() {
  4. User user=userRepository.findByUserName("aa");
  5. System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
  6. return user;
  7. }

其中value的值就是缓存到redis中的key

5.序列化,反序列化

springData还提供了其他的序列化方式,如下:

  1. GenericJackson2JsonRedisSerializer.class
  2. GenericToStringSerializer.class
  3. Jackson2JsonRedisSerializer.class
  4. JacksonJsonRedisSerializer.class
  5. JdkSerializationRedisSerializer.class
  6. OxmSerializer.class
  7. RedisSerializer.class
  8. SerializationException.class
  9. SerializationUtils.class
  10. StringRedisSerializer.class
  11.  
  12. GenericToStringSerializer:使用Spring转换服务进行序列化;
    JacksonJsonRedisSerializer:使用Jackson 1,将对象序列化为JSON
    Jackson2JsonRedisSerializer:使用Jackson 2,将对象序列化为JSON
    JdkSerializationRedisSerializer:使用Java序列化;
    OxmSerializer:使用Spring O/X映射的编排器和解排器(marshalerunmarshaler)实现序列化,用于XML序列化;
    StringRedisSerializer:序列化String类型的keyvalue。实际上是Stringbyte数组之间的转换

6. 遇到的报错:

  1. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<?, ?>' available: expected at least bean which qualifies as autowire candidate. Dependency annotations: {}
  2. at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
  3. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
  4. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
  5. at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
  6. at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
  7. ... common frames omitted

【转载】Springboot整合 一 集成 redis的更多相关文章

  1. Springboot 2.0 - 集成redis

    序 最近在入门SpringBoot,然后在感慨 SpringBoot较于Spring真的方便多时,顺便记录下自己在集成redis时的一些想法. 1.从springboot官网查看redis的依赖包 & ...

  2. SpringBoot(十)_springboot集成Redis

    Redis 介绍 Redis是一款开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存也可持久化的日志型.Key-Value高性能数据库. 数据模型 Redis 数据模型不仅与关系数据 ...

  3. springboot整合mybatis,mongodb,redis

    springboot整合常用的第三方框架,mybatis,mongodb,redis mybatis,采用xml编写sql语句 mongodb,对MongoTemplate进行了封装 redis,对r ...

  4. springBoot整合Spring-Data-JPA, Redis Redis-Desktop-Manager2020 windows

    源码地址:https://gitee.com/ytfs-dtx/SpringBoot Redis-Desktop-Manager2020地址: https://ytsf.lanzous.com/b01 ...

  5. springboot 2.X 集成redis

    在实际开发中,经常会引入redis中间件做缓存,这里介绍springboot2.X后如何配置redis 1 Maven中引入redis springboot官方通过spring-boot-autoco ...

  6. 转载-Springboot整合ehcache缓存

    转载:https://www.cnblogs.com/xzmiyx/p/9897623.html EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来, 是进程中的缓存系统 ...

  7. springboot(七).springboot整合jedis实现redis缓存

    我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高速缓存来缓存一些数据,存储一些高频率访问的数据,如果直接使用redis的话又比较麻烦,在这里,我们使用jedis来实现r ...

  8. springboot整合logback集成elk实现日志的汇总、分析、统计和检索功能

    在Spring Boot当中,默认使用logback进行log操作.logback支持将日志数据通过提供IP地址.端口号,以Socket的方式远程发送.在Spring Boot中,通常使用logbac ...

  9. SpringBoot整合Shiro自定义Redis存储

    Shiro Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 Subject. SecurityManager. Realms,公共部分 Shiro 都已经为我们封装好了,我们 ...

随机推荐

  1. hdu 1542

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=1542 题意: 求所给矩形的覆盖面积 题解: 利用扫描线的思想,先将坐标离散化,之后以y轴分成多个矩形求解, ...

  2. 007 关于Spark下的第二种模式——standalone搭建

    一:介绍 1.介绍standalone Standalone模式是Spark自身管理资源的一个模式,类似Yarn Yarn的结构: ResourceManager: 负责集群资源的管理 NodeMan ...

  3. [CodeForces-1036E] Covered Points 暴力 GCD 求交点

    题意: 在二维平面上给出n条不共线的线段,问这些线段总共覆盖到了多少个整数点 解法: 用GCD可求得一条线段覆盖了多少整数点,然后暴力枚举线段,求交点,对于相应的 整数交点,结果-1即可 #inclu ...

  4. hdu 1686 Oulipo 【KMP】(计算模式串匹配的次数——与已匹配的字串可以有交集)

    题目链接:https://vjudge.net/contest/220679#problem/B 题目大意: 输入一个T,表示有T组测试数据: 每组测试数据包括一个字符串W,T,T长度大于W小于100 ...

  5. Linux开源监控平台 -- Zabbix 小白安装以及使用

    安装准备: 1.安装前需要先关闭selinux和firewall. 关闭Linux: [root@zabbix ~]# vi /etc/selinux/config 将SELINUX=enforcin ...

  6. MySQL数据库基本用法

    远程连接数据库 mysql -u root -p #-u 用户名 -h后面写要连接的主机ip地址 -u后面写连接的用户名 -p回车后写密码 回车后输入密码,当前设置的密码为toor 数据库操作 创建数 ...

  7. 7,EasyNetQ-控制队列名称

    EasyNetQ在为队列生成名称时的默认行为是使用   消息类型名称+subscription Id 例如,名称空间EasyNetQ.Tests.Integration中的PartyInvitatio ...

  8. 运行程序,解读this指向---case2

    片段1 var anum = 666; function funcTest1(){ var b = anum * 2; var anum = 6; var c = anum / 2; console. ...

  9. HDU.1536.S-Nim(博弈论 Nim)

    题目链接 \(Description\) 给定一个集合S,每次只能拿S中某个元素个数的石子.每组数据有多组询问,询问给出m堆石子个数,问先手是否必胜.有多组数据. 1. 首先对操作数组排个序,再预处理 ...

  10. IETester是一个免费的Web浏览器调试工具

    功能简介 IETester是一个免费的Web浏览器调试工具,可以模拟出不同的js引擎来帮助程序员设计效果统一的代码.IETester可以在独立的标签页中开启IE5.5.IE6.IE7以及最I新的IE8 ...