【转载】Springboot整合 一 集成 redis
原文: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
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2、添加配置文件
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
3、添加cache的配置类
StringRedisTemplate默认采用的key序列化方式为setKeySerializer(stringSerializer);此时在使用Spring的缓存注解如@Cacheable的key属性设置值时,就需
要注意如果参数类型为Long那么会出不能进行String类型转换异常。
RedisTemplate默认使用的序列化方式为JdkSerializationRedisSerializer,它就没有上边的问题。因为它的序列化方法为serialize(Object object)
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
如果你只需要使用基本的redis配置,那么使用如下配置类即可,spring boot会自动扫描redis的基本配置,但是有一项要注意那就是password,如果你在配置文件中设置了password,那么就必须在配置类中手工注入JedisConnectionFactory中,否则会在启动过程中报NOAUTH Authentication required.;:
- @Bean
- public JedisConnectionFactory redisConnectionFactory() {
- JedisConnectionFactory factory = new JedisConnectionFactory();
- factory.setHostName(host);
- factory.setPort(port);
- factory.setPassword(password);
- factory.setTimeout(timeout); //设置连接超时时间
- //连接池配置
- JedisPoolConfig poolConfig = new JedisPoolConfig();
- poolConfig.setMinIdle(minIdle);
- poolConfig.setMaxIdle(maxIdle);
- poolConfig.setMaxTotal(maxTotal);
- poolConfig.setMaxWaitMillis(maxWait);
- factory.setPoolConfig(poolConfig);
- return factory;
- }
- JedisPoolConfig config = new JedisPoolConfig();
- //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
- config.setBlockWhenExhausted(true);
- //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
- config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
- //是否启用pool的jmx管理功能, 默认true
- config.setJmxEnabled(true);
- //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
- config.setJmxNamePrefix("pool");
- //是否启用后进先出, 默认true
- config.setLifo(true);
- //最大空闲连接数, 默认8个
- config.setMaxIdle(8);
- //最大连接数, 默认8个
- config.setMaxTotal(8);
- //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
- config.setMaxWaitMillis(-1);
- //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
- config.setMinEvictableIdleTimeMillis(1800000);
- //最小空闲连接数, 默认0
- config.setMinIdle(0);
- //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
- config.setNumTestsPerEvictionRun(3);
- //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略)
- config.setSoftMinEvictableIdleTimeMillis(1800000);
- //在获取连接的时候检查有效性, 默认false
- config.setTestOnBorrow(false);
- //在空闲时检查有效性, 默认false
- config.setTestWhileIdle(false);
- //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
- config.setTimeBetweenEvictionRunsMillis(-1);
3、好了,接下来就可以直接使用了,测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() throws Exception {
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
}
@Test
public void testObj() throws Exception {
User user=new User("aa@126.com", "aa", "aa123456", "aa","123");
ValueOperations<String, User> operations=redisTemplate.opsForValue();
operations.set("com.neox", user);
operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
Thread.sleep(1000);
//redisTemplate.delete("com.neo.f");
boolean exists=redisTemplate.hasKey("com.neo.f");
if(exists){
System.out.println("exists is true");
}else{
System.out.println("exists is false");
}
// Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
}
}
以上都是手动使用的方式,如何在查找数据库的时候自动使用缓存呢,看下面;
4、自动根据方法生成缓存
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}
其中value的值就是缓存到redis中的key
5.序列化,反序列化
springData还提供了其他的序列化方式,如下:
- GenericJackson2JsonRedisSerializer.class
- GenericToStringSerializer.class
- Jackson2JsonRedisSerializer.class
- JacksonJsonRedisSerializer.class
- JdkSerializationRedisSerializer.class
- OxmSerializer.class
- RedisSerializer.class
- SerializationException.class
- SerializationUtils.class
- StringRedisSerializer.class
- GenericToStringSerializer:使用Spring转换服务进行序列化;
JacksonJsonRedisSerializer:使用Jackson 1,将对象序列化为JSON;
Jackson2JsonRedisSerializer:使用Jackson 2,将对象序列化为JSON;
JdkSerializationRedisSerializer:使用Java序列化;
OxmSerializer:使用Spring O/X映射的编排器和解排器(marshaler和unmarshaler)实现序列化,用于XML序列化;
StringRedisSerializer:序列化String类型的key和value。实际上是String和byte数组之间的转换
6. 遇到的报错:
- 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: {}
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
- at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
- at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
- at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:) ~[spring-beans-4.3..RELEASE.jar:4.3..RELEASE]
- ... common frames omitted
【转载】Springboot整合 一 集成 redis的更多相关文章
- Springboot 2.0 - 集成redis
序 最近在入门SpringBoot,然后在感慨 SpringBoot较于Spring真的方便多时,顺便记录下自己在集成redis时的一些想法. 1.从springboot官网查看redis的依赖包 & ...
- SpringBoot(十)_springboot集成Redis
Redis 介绍 Redis是一款开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存也可持久化的日志型.Key-Value高性能数据库. 数据模型 Redis 数据模型不仅与关系数据 ...
- springboot整合mybatis,mongodb,redis
springboot整合常用的第三方框架,mybatis,mongodb,redis mybatis,采用xml编写sql语句 mongodb,对MongoTemplate进行了封装 redis,对r ...
- springBoot整合Spring-Data-JPA, Redis Redis-Desktop-Manager2020 windows
源码地址:https://gitee.com/ytfs-dtx/SpringBoot Redis-Desktop-Manager2020地址: https://ytsf.lanzous.com/b01 ...
- springboot 2.X 集成redis
在实际开发中,经常会引入redis中间件做缓存,这里介绍springboot2.X后如何配置redis 1 Maven中引入redis springboot官方通过spring-boot-autoco ...
- 转载-Springboot整合ehcache缓存
转载:https://www.cnblogs.com/xzmiyx/p/9897623.html EhCache是一个比较成熟的Java缓存框架,最早从hibernate发展而来, 是进程中的缓存系统 ...
- springboot(七).springboot整合jedis实现redis缓存
我们在使用springboot搭建微服务的时候,在很多时候还是需要redis的高速缓存来缓存一些数据,存储一些高频率访问的数据,如果直接使用redis的话又比较麻烦,在这里,我们使用jedis来实现r ...
- springboot整合logback集成elk实现日志的汇总、分析、统计和检索功能
在Spring Boot当中,默认使用logback进行log操作.logback支持将日志数据通过提供IP地址.端口号,以Socket的方式远程发送.在Spring Boot中,通常使用logbac ...
- SpringBoot整合Shiro自定义Redis存储
Shiro Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 Subject. SecurityManager. Realms,公共部分 Shiro 都已经为我们封装好了,我们 ...
随机推荐
- hdu 1542
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1542 题意: 求所给矩形的覆盖面积 题解: 利用扫描线的思想,先将坐标离散化,之后以y轴分成多个矩形求解, ...
- 007 关于Spark下的第二种模式——standalone搭建
一:介绍 1.介绍standalone Standalone模式是Spark自身管理资源的一个模式,类似Yarn Yarn的结构: ResourceManager: 负责集群资源的管理 NodeMan ...
- [CodeForces-1036E] Covered Points 暴力 GCD 求交点
题意: 在二维平面上给出n条不共线的线段,问这些线段总共覆盖到了多少个整数点 解法: 用GCD可求得一条线段覆盖了多少整数点,然后暴力枚举线段,求交点,对于相应的 整数交点,结果-1即可 #inclu ...
- hdu 1686 Oulipo 【KMP】(计算模式串匹配的次数——与已匹配的字串可以有交集)
题目链接:https://vjudge.net/contest/220679#problem/B 题目大意: 输入一个T,表示有T组测试数据: 每组测试数据包括一个字符串W,T,T长度大于W小于100 ...
- Linux开源监控平台 -- Zabbix 小白安装以及使用
安装准备: 1.安装前需要先关闭selinux和firewall. 关闭Linux: [root@zabbix ~]# vi /etc/selinux/config 将SELINUX=enforcin ...
- MySQL数据库基本用法
远程连接数据库 mysql -u root -p #-u 用户名 -h后面写要连接的主机ip地址 -u后面写连接的用户名 -p回车后写密码 回车后输入密码,当前设置的密码为toor 数据库操作 创建数 ...
- 7,EasyNetQ-控制队列名称
EasyNetQ在为队列生成名称时的默认行为是使用 消息类型名称+subscription Id 例如,名称空间EasyNetQ.Tests.Integration中的PartyInvitatio ...
- 运行程序,解读this指向---case2
片段1 var anum = 666; function funcTest1(){ var b = anum * 2; var anum = 6; var c = anum / 2; console. ...
- HDU.1536.S-Nim(博弈论 Nim)
题目链接 \(Description\) 给定一个集合S,每次只能拿S中某个元素个数的石子.每组数据有多组询问,询问给出m堆石子个数,问先手是否必胜.有多组数据. 1. 首先对操作数组排个序,再预处理 ...
- IETester是一个免费的Web浏览器调试工具
功能简介 IETester是一个免费的Web浏览器调试工具,可以模拟出不同的js引擎来帮助程序员设计效果统一的代码.IETester可以在独立的标签页中开启IE5.5.IE6.IE7以及最I新的IE8 ...