【转载】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 都已经为我们封装好了,我们 ...
随机推荐
- usaco 校园网
题解: 显然当一个图上的点是一个环时能满足题目要求 那么我们来考虑怎么形成一个环 很显然的是要先缩点 缩完点就成为了森林,如何让森林成环呢? 考虑一下环上的点的入度出度一定都大于1 而连一条边可以增加 ...
- PhotoShop 常用快捷键
PhotoShop: ctrl+j 复制一块图层ctrl+t 自由变换钢笔画出来的是路径不是选区,将路径转化成选区:ctrl+回车 alt+delete 直排文字蒙版ctrl+d 取消选择中括号可改变 ...
- UVA725 Division 除法【暴力】
题目链接>>>>>> 题目大意:给你一个数n(2 <= n <= 79),将0-9这十个数字分成两组组成两个5位数a, b(可以包含前导0,如02345 ...
- Couple number
P1348 Couple number 我其实找规律了的,然后也没仔细分析,这个题多巧妙. C=a^2-b^2=(a+b)(a-b) 对于任意a而言,加减同一个数得到的数的奇偶性相同,故c=奇数或4的 ...
- Flutter常用组件(Widget)解析-Image
显示图片的组件 以下是几种加载图片路径方式: Image.asset 加载asset项目资源中的文件 Image.network 加载网络资源图片,通过url加载 Image.file 加载本地文件中 ...
- 上线---苹果AppStore审核注意事项,Guideline 1.2 - Safety - User Generated Content,2.1等条例(苹果审核六次拒绝)
前段时间上线app,和战友一起撸了那么久的代码,上线是最激动的.然而安卓各大平台上线了半个月了,苹果却给了六次拒绝. 刚开始等苹果等的焦头烂额,现在内心毫无波澜,目前还在审核中...... 六次的拒绝 ...
- python-线程的暂停, 恢复, 退出
我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦s ...
- 多个 gradle 文件夹 \.gradle\wrapper\dists\ 设置gradle不是每次都下载
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 设置gradle不是每次都下载 \.gradle\wrapper\dists\ ==== ...
- LOJ.6281.数列分块入门5(分块 区间开方)
题目链接 int内的数(也不非得是int)最多开方4.5次就变成1了,所以还不是1就暴力,是1就直接跳过. #include <cmath> #include <cstdio> ...
- [HDU5361]In Touch
[HDU5361]In Touch 题目大意: 有\(n(n\le2\times10^5)\)个点,每个点有三个属性\(l_i,r_i,c_i\).表示若\(|i-j|\in[l_i,r_i]\),\ ...