Spring boot(三)在Spring boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化。
redis介绍
Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍Redis在Spring Boot中两个典型的应用场景。
如何使用
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的配置类
@Configuration
//此注解会调用Spring boot的RedisAutoConfiguration来初始化RedisTemplate和StringRedisTemplate
@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;
}
}
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
共享Session-spring-session-data-redis
分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一,
Spring Session官方说明
Spring Session provides an API and implementations for managing a user’s session information.
如何使用
1、引入依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2、Session配置:
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}
maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效
好了,这样就配置好了,我们来测试一下
3、测试
添加测试方法获取sessionid
@RequestMapping("/uid")
String uid(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}
登录redis 输入 keys '*sessions*'
t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4
t(spring:session:expirations:1472976480000
其中 1472976480000为失效时间,意思是这个时间后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 为sessionId,登录http://localhost:8080/uid 发现会一致,就说明session 已经在redis里面进行有效的管理了。
如何在两台或者多台中共享session
其实就是按照上面的步骤在另一个项目中再次配置一次,启动后自动就进行了session共享。
Spring boot(三)在Spring boot中Redis的使用的更多相关文章
- spring boot(三):Spring Boot中Redis的使用
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
- (转)Spring Boot(三):Spring Boot 中 Redis 的使用
http://www.ityouknow.com/springboot/2016/03/06/spring-boot-redis.html Spring Boot 对常用的数据库支持外,对 Nosql ...
- Spring Boot(三):Spring Boot 中 Redis 的使用
Spring Boot 对常用的数据库支持外,对 Nosql 数据库也进行了封装自动化. Redis 介绍 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更 ...
- Spring系列(三):Spring IoC中各个注解的理解和使用
原文链接:1. http://www.cnblogs.com/xdp-gacl/p/3495887.html 2. http://www.cnblogs.com/xiaoxi/p/5935 ...
- Spring Boot(三):Spring Boot中的事件的使用 与Spring Boot启动流程(Event 事件 和 Listeners监听器)
前言:在讲述内容之前 希望大家对设计模式有所了解 即使你学会了本片的内容 也不知道什么时候去使用 或者为什么要这样去用 观察者模式: 观察者模式是一种对象行为模式.它定义对象间的一种一对多的依赖关系, ...
- spring boot(三):spring data jpa的使用
@RequestMapping("/queryUserListByPageNativeQuery") public String queryUserListByPageNative ...
- 攻城狮在路上(贰) Spring(三)--- Spring 资源访问利器Resource接口
Spring为了更好的满足各种底层资源的访问需求.设计了一个Resource接口,提供了更强的访问底层资源的能力.Spring框架使用Resource装载各种资源,包括配置文件资源.国际化属性文件资源 ...
- Spring ( 三 ) Spring的Bean的装配与生命周期、专用测试
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 一.对象的生命周期 1.IOC之Bean的生命周期 创建带有生命周期方法的bean public cla ...
- Spring(三)--Spring bean的生命周期
Spring bean的生命周期 ApplicationContext Bean生命周期流程 1.需要的实体类 ackage com.xdf.bean; import org.springframew ...
随机推荐
- python 之 循环语句
python提供了for循环和while循环以及嵌套循环(在python中没有do..while循环) while 循环语法: while 判断条件: 执行语句...... 实际案例: numbers ...
- 题解——loj6280 数列分块入门4 (分块)
分块维护一个区间和 然后记得更新的时候左边角块的tag不要打错到右边角块 #include <cstdio> #include <algorithm> #include < ...
- (转载)c# winform 窗体起始位置 设置
窗体起始位置为顶部中间,WinForm居中显示: ; ; this.StartPosition = FormStartPosition.Manual; //窗体的位置由Location属性决定 thi ...
- SAP月结操作讲解
SAP月结操作讲解 https://wenku.baidu.com/view/ac6fe45d312b3169a451a4b9.html 步聚 操作内容 事务码 是否必须 操作时间 月/年结 1 ...
- 20165306 预备作业3 Linux安装及学习
查看了许多教程,VirtualBox和Ubuntu已安装完成.以下为学习Linux基础入门课程的实验报告.实验截图.尚未解决的问题及体会. 实验三 用户及文件权限管理 一.Linux用户管理 (一)查 ...
- 每日质量NPM包事件绑定_bindme(详解React的this)
一.bindme 官方定义: is a helper to bind a list of methods to an object reference 理解: 因为不推荐在render()里构建函数, ...
- 利用logstash从mysql同步数据到ElasticSearch
前面一篇已经把logstash和logstash-input-jdbc安装好了. 下面就说下具体怎么配置. 1.先在安装目录bin下面(一般都是在bin下面)新建两个文件jdbc.conf和jdbc. ...
- HTTP是什么连接
① 在HTTP/1.0中,默认使用的是短连接. 但从 HTTP/1.1起,默认使用长连接,用以保持连接特性. ②http长连接并不是一直保持连接 http的长连接也不会是永久保持连接,它有一个保持时间 ...
- centos7 Python3终端中敲击方向键显示「^[[C^[[D」
[root@localhost src]# python3 Python ( , ::) [GCC (Red Hat -)] on linux Type "help", " ...
- python中字典的用法
一,字典的简单介绍概念: 字典(dict)是python中唯一的一个映射类型.他是以{ }括起来的键值对组成. 在dict中key是 唯一的. 在保存的时候, 根据key来计算出一个内存地址. 然后将 ...