Spring boot(3):Spring boot中Redis 的使用

Spring boot除了常用的数据库支持外,对nosql数据库也进行了封装自动化。

1 Redis介绍


Redis 是目前业界使用最广泛的内存数据存储。相比memcached,
(1)Redis支持更丰富的数据结构,例如hashes,lists,sets等,同时支持数据持久化。
(2)除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性

因此有着丰富的应用场景。介绍两个Redis在Spring boot项目中的典型应用场景。

1.1 如何使用

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
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{@Beanpublic KeyGenerator keyGenerator() { return new KeyGenerator() {           @Overridepublic 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") @Beanpublic CacheManager cacheManager(RedisTemplate redisTemplate) {RedisCacheManager rcm = new RedisCacheManager(redisTemplate);        //设置缓存过期时间//rcm.setDefaultExpiration(60);//秒return rcm;}@Beanpublic 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;}}

4 好了,接下来就可以直接使用了

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis {   @Autowiredprivate StringRedisTemplate stringRedisTemplate;@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void test() throws Exception {stringRedisTemplate.opsForValue().set("aaa", "111");Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));}    @Testpublic 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 好了,接下来就可以直接使用了

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis {   @Autowiredprivate StringRedisTemplate stringRedisTemplate;@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void test() throws Exception {stringRedisTemplate.opsForValue().set("aaa", "111");Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));}    @Testpublic 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")		//Redis获取key的值
public User getUser() {User user=userRepository.findByUserName("aa");System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");  return user;
}

1.2 共享session-spring-session-data-redis

分布式系统中,session共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一。

spring session官方说明

spring session provide an API and implementation 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的sever.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-b137a3ed6bc4t(spring:session:expirations:1472976480000

其中 1472976480000为失效时间,意思是这个时间后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4t 为sessionid,登录http://localhost:8080/uid发现会一致,就说明session 已经在redis里面进行有效的管理了。

如何在两台或者多台中共享session

其实就是按照上面的步骤在另一个项目中再次配置一次,启动后就进行了session共享。本文所有示例:https://github.com/ityouknow/spring-boot-starter

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/330973.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java List面试题汇总

转载自 Java List面试题汇总 1、你知道的List都有哪些&#xff1f; 2、List和Vector有什么区别&#xff1f; 3、List是有序的吗&#xff1f; 4、ArrayList和LinkedList的区别&#xff1f;分别用在什么场景&#xff1f; 5、ArrayList和LinkedList的底层数据结构是什么&#…

ReviewForJob——拓扑排序+最短路径算法(有权+无权)

【0】README 1&#xff09;本文旨在给出 拓扑排序最短路径算法&#xff08;有权无权&#xff09; 的源码实现 和 分析&#xff0c;内容涉及到 邻接表&#xff0c; 拓扑排序&#xff0c; 循环队列&#xff0c;无权最短路径&#xff08;广度优先搜索&#xff09;&#xff0c;有权…

Spring boot (5):Spring data jpa 的使用

总结&#xff1a; jpa是什么&#xff0c;spring data jpa是什么&#xff1f; jpa是一套规范&#xff0c;不是一套产品。jpa是一套规范&#xff0c;不是一套产品。 spring data jpa是spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架&#xff0c;提供了包括增删改等在…

Java Map集合面试题汇总

转载自 Java Map集合面试题汇总1、 你都知道哪些常用的Map集合?2、Collection集合接口和Map接口有什么关系&#xff1f;3、HashMap是线程安全的吗&#xff1f;线程安全的Map都有哪些&#xff1f;性能最好的是哪个&#xff1f;4、使用HashMap有什么性能问题吗&#xff1f;5、Ha…

ReviewForJob——二叉堆优先队列的实现(三种堆节点类型——int + struct HeapNode + struct HeapNode*)

【0】README 1&#xff09;本文旨在给出 二叉堆优先队列的实现 的代码实现和分析&#xff0c; 而堆节点类型 不外乎三种&#xff1a; 一&#xff0c; 基本类型如int&#xff1b; 二&#xff0c;结构体类型 struct HeapNode&#xff1b; 三&#xff0c;结构体指针类型 struct H…

Spring boot(六):如何优雅的使用mybatis

总结 hibernate 和 mybatis 的区别 hibernate的特点是所有的sql都用java代码生成&#xff0c;不用跳出程序去&#xff08;看&#xff09;sql&#xff0c;发展到最顶端就是Spring data jpa了。 mybatis初期使用比较麻烦&#xff0c;需要各种配置文件、实体类、dao层映射关联、还…

Java中创建String的两道面试题及详解

转载自 Java中创建String的两道面试题及详解 我们知道创建一个String类型的变量一般有以下两种方法&#xff1a; String str1 "abcd";String str2 new String("abcd"); 那么为什么会存在这两种创建方式呢&#xff0c;它们在内存中的表现形式各有什么区别…

ReviewForJob——最小生成树(prim + kruskal)源码实现和分析

【0】README 1&#xff09;本文旨在给出 ReviewForJob——最小生成树&#xff08;prim kruskal&#xff09;源码实现和分析&#xff0c; 还会对其用到的 技术 做介绍&#xff1b; 2&#xff09;最小生成树是对无向图而言的&#xff1a;一个无向图G 的最小生成树是一个连通图…

Spring boot(七):Spring boot+ mybatis 多数据源最简解决方案

多数据源一般解决哪些问题&#xff1f;主从模式或者业务比较复杂需要连接不同的分库来支持业务。 直接上代码。 配置文件 pom包依赖&#xff0c;该依赖的依赖。主要是数据库这边的配置&#xff1a; mybatis.config-locationsclasspath:mybatis/mybatis-config.xmlspring.da…

Java:关于main方法的10道面试题

转载自 Java&#xff1a;关于main方法的10道面试题 1.main方法是做什么用的&#xff1f; 2.不用main方法如何运行一个类&#xff1f; 3.main方法如何传递参数&#xff1f;传递参数的类型是什么&#xff1f;能不能改变该参数类型&#xff1f; 4.main方法为什么是静态的&#xff…

ReviewForJob——深度优先搜索的应用

【0】README 1&#xff09;本文旨在 介绍 ReviewForJob——深度优先搜索的应用 及其 源码实现 &#xff1b; 2&#xff09;搜索树的技术分为广度优先搜索 和 深度优先搜索&#xff1a;而广度优先搜索&#xff0c;我们前面利用 广度优先搜索计算无权最短路径已经做过分析了&am…

Spring boot(八):RabbitMQ详解

RabbitMQ介绍 RabbitMQ既一个消息队列&#xff0c;主要用来实现应用程序的异步和解耦&#xff0c;同时也能起到消息缓冲&#xff0c;消息分发的作用。 消息中间件在互联网公司的使用中越来越多。消息中间件最主要的作用是解耦&#xff0c;中间件最标准的用法师生产者生产消息传…

关于Jvm知识看这一篇就够了

转载自 关于Jvm知识看这一篇就够了2016年左右的时候读了周志明《深入理解Java虚拟机&#xff1a;JVM高级特性与最佳实践》&#xff0c;读完之后受益匪浅&#xff0c;让我对Java虚拟机有了一个完整的认识&#xff0c;这是Jvm书籍中最好的读物之一。后来结合实际工作中遇到的问题…

ReviewForJob——算法设计技巧(贪婪算法+分治算法+动态规划)

【0】README 1&#xff09;本文旨在介绍算法设计技巧包括 贪婪算法、分治算法、动态规划 以及相关的荔枝等&#xff1b; 【1】贪婪算法 1&#xff09;intro&#xff1a; 贪婪算法是分阶段进行的&#xff0c;在每个阶段&#xff0c;可以认为所做的决定是最好的&#xff0c;而…

Spring boot(九):定时任务

在我们的项目开发过程中&#xff0c;进场需要定时任务来帮助我们做一些内容&#xff0c;springboot默认已经帮我们实行了&#xff0c;只要天剑相应的注解就可以实现。 1、pom包配置 pom包里面只需要引入springboot starter包即可 <dependencies><dependency><…

jvm系列(一):java类的加载机制

转载自 jvm系列(一):java类的加载机制1、什么是类的加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中&#xff0c;将其放在运行时数据区的方法区内&#xff0c;然后在堆区创建一个 java.lang.Class对象&#xff0c;用来封装类在方法区内的数据结构。类的加载的最…

Springboot(十):邮件服务

发送邮件应该是网站的必备功能之一&#xff0c;什么注册验证&#xff0c;忘记密码或者是给用户发送营销信息。最早期的时候我们会使用javaMail相关api来写邮件相关代码&#xff0c;后来spring退出了javaMailSender 更加简化了邮件发送的过程&#xff0c;在之后springboot 对此进…

How to install plugin for Eclipse from .zip

these contents are reshiped from 如何在eclipse中安装.zip插件 1.make sure your .zip file is an valid Eclipse Plugin Note: that means: your .zip file contains folders features and plugins, like this:for new version Eclipse Plugin, it may also include anothe…

jvm系列(二):JVM内存结构

转载自 jvm系列(二):JVM内存结构所有的Java开发人员可能会遇到这样的困惑&#xff1f;我该为堆内存设置多大空间呢&#xff1f;OutOfMemoryError的异常到底涉及到运行时数据的哪块区域&#xff1f;该怎么解决呢&#xff1f;其实如果你经常解决服务器性能问题&#xff0c;那么这…

jvm系列(三):GC算法 垃圾收集器

转载自 jvm系列(三):GC算法 垃圾收集器 概述 垃圾收集 Garbage Collection 通常被称为“GC”&#xff0c;它诞生于1960年 MIT 的 Lisp 语言&#xff0c;经过半个多世纪&#xff0c;目前已经十分成熟了。 jvm 中&#xff0c;程序计数器、虚拟机栈、本地方法栈都是随线程而生随线…