【转载】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 都已经为我们封装好了,我们 ...
随机推荐
- centos7网卡名修改
centos7网卡名不是以etho的方式命名,有时候在自动化方面不便于管理,在安装的时候输入如下代码即可命名: net.ifnames=0 biosdevname=0
- Codeforces 269C Flawed Flow (看题解)
我好菜啊啊啊.. 循环以下操作 1.从队列中取出一个顶点, 把哪些没有用过的边全部用当前方向. 2.看有没有点的入度和 == 出度和, 如果有将当前的点加入队列. 现在有一个问题就是, 有没有可能队列 ...
- 基于kubernetes集群部署DashBoard
目录贴:Kubernetes学习系列 在之前一篇文章:Centos7部署Kubernetes集群,中已经搭建了基本的K8s集群,本文将在此基础之上继续搭建K8s DashBoard. 1.yaml文件 ...
- P1219 八皇后 含优化 1/5
题目描述 检查一个如下的6 x 6的跳棋棋盘,有六个棋子被放置在棋盘上,使得每行.每列有且只有一个,每条对角线(包括两条主对角线的所有平行线)上至多有一个棋子. 上面的布局可以用序列2 4 6 1 3 ...
- oracle中tables和views的区别
tables存储的行和列的数据,可以做任何操作 views存储的是算法,是虚拟的数据
- 二分搜索-poj2785
题目链接:http://poj.org/problem?id=2785 题目大意:要求输入A,B,C,D四个数组,从每个数组中分别取出一个数来相加,求出相加后 和为0 总共有多少种加法. #inclu ...
- 玩转SpringCloud(F版本) 三.断路器(Hystrix)RestTemplate+Ribbon和Feign两种方式
此文章基于: 玩转SpringCloud 一.服务的注册与发现(Eureka) 玩转SpringCloud 二.服务消费者(1)ribbon+restTemplate 转SpringCloud 二.服 ...
- Web大前端面试题-Day5
1.写一个深度克隆方法(es5)? /** * 深拷贝 * @param {object}fromObj 拷贝的对象 * @param {object}toObj 目标对象 */ function ...
- 安卓 运行、调试 配置 android Run/debug configurations
android 运行.调试 配置 android Run/debug configurations 作者:韩梦飞沙 Author:han_meng_fei_sha 邮箱:313134555@qq. ...
- 通过css实现小三角形
下面是用css做小三角形的demo, <!DOCTYPE html><html lang="en"><head> <meta charse ...