SpringBoot之使用Lettuce集成Redis
一、Lettuce
Redis这里就不多说,服务端的启动之前的博客里面也有提到,这里略过。Lettuce和Jedis都是连接Redis Server的客户端程序,Jedis在实现上是直连redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
二、maven依赖
还是按照原来的步骤,先是导入依赖,然后配置属性,最后实例,其实使用springboot都是差不多的步骤。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
三、属性配置
这里使用的是lettuce,如果使用Jedis,把下面的lettuce改成Jedis就好。
spring.redis.host=127.0.0.1 spring.redis.password= spring.redis.port= 6379 spring.redis.timeout=1000 spring.redis.database=0 spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.max-active=8
四、实例
这里还是在之前demo的基础上进行修改.默认情况下的模板只能支持StringRedisTemplate<String,String>,只能存字符串。这时需要自定义模板,当自定义模板后又想存储String字符串时,可以使用RedisTemplate的方式,他们俩并不冲突。在RedisCacheAutoConfiguration中自定义了一个RedisTemplate。
package com.example.config; import java.io.Serializable; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
在User类中增加了构造函数。
package com.example.model;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public String toString() {
// TODO Auto-generated method stub
return "User [id=" + Id + ", name=" + Name + ", age=" + Age + "]";
}
public User(String id, String name, int age, UserSexEnum sex) {
super();
Id = id;
Name = name;
Age = age;
Sex = sex;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
private String Id;
private String Name;
private int Age;
private UserSexEnum Sex;
public UserSexEnum getSex() {
return Sex;
}
public void setSex(UserSexEnum sex) {
Sex = sex;
}
}
修改之前demo中的UserController,在里面注入StringRedisTemplate和RedisTemplate用来测试。增加的主要代码是39-46行处。
package com.example.demo; import java.io.Serializable;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.example.model.User;
import com.example.model.UserSexEnum;
import com.example.read.mapper.ReadUserMapper;
import com.example.write.mapper.WriteUserMapper; @Controller
@RequestMapping("/user")
public class UserController { @Autowired
private WriteUserMapper userMapperWrite; @Autowired
private ReadUserMapper userMapperRead; @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate<String, Serializable> redisCacheTemplate; @RequestMapping(value = "/alluser.do",method = RequestMethod.GET)
public String getallusers(Model model) {
List<User> users=userMapperRead.getAll();
model.addAttribute("users", users);
stringRedisTemplate.opsForValue().set("keytest", "cuiyw");
final String keytest = stringRedisTemplate.opsForValue().get("keytest");
model.addAttribute("keytest", keytest);
String key = "1857XXXX040";
redisCacheTemplate.opsForValue().set(key, new User(key, "cuiyw", 18, UserSexEnum.MAN));
// TODO 对应 String(字符串)
final User user = (User) redisCacheTemplate.opsForValue().get(key);
model.addAttribute("user", user);
return "userlist";
}
@RequestMapping(value = "/insert.do",method = RequestMethod.GET)
public String adduser(Model model) {
User user=new User();
user.setName("cuiyw");
user.setAge(27);
userMapperWrite.insert(user);
List<User> users=userMapperWrite.getAll();
model.addAttribute("users", users);
return "userlist";
}
}
打开url:http://localhost:8080/user/alluser.do,可以看到从redis获取的String类型的key和User对象。

五、错误
这里在打开url时报了一个redis连接超时的错误io.lettuce.core.RedisCommandTimeoutException: Command timed out,我开始以为是设置的timeout太小导致的,可我设置到10000时还是报错,后来又回顾了下之前redis server启动的方法,启动时增加redis.windows.conf,使用redis-server.exe redis.windows.conf启动后居然可以了,可能是我之前双击启动有问题导致的。
这里只是实现Redis的简单使用,在实际项目中还要有集群以及结合cache来一起使用的场景,后续再慢慢补充。
周末兄弟离开深圳,现在只剩我一个,想想三哥们一起从漯河分开,一个为了爱情去了重庆,我们两个一起来的深圳,在从之前5个同学,到现在只剩下我一个,觉得时间过得好快,就像昨天发生的一样,淡淡的忧伤。这里也祝兄弟在新的城市开辟新的天地!
SpringBoot之使用Lettuce集成Redis的更多相关文章
- SpringBoot(十一): Spring Boot集成Redis
1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...
- SpringBoot 2.X以上集成redis
在网上看到的教程和资料大多数都是2.X以下的版本.使用起来会出现各种问题,通过百度,最后终于弄好了. 2.x以上使用的是 spring-boot-starter-data-redis 2.x一下使用的 ...
- SpringBoot集成Redis来实现缓存技术方案
概述 在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. ...
- Spring Boot 2.X(六):Spring Boot 集成Redis
Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...
- 【原创】SpringBoot 2.7.0通过lettuce及commons-pool2 v2.9.0集成Redis踩坑记录
背景 公司的一个项目由于HTTPS证书到期,导致小程序.POS不能正常使用.所以百度了下,通过URL检测证书有效期的代码,并自行整合到一个服务中. 代码仓库:[基于SpringBoot + 企业微信 ...
- Springboot 2.0.x 集成基于Centos7的Redis集群安装及配置
Redis简介 Redis是一个基于C语言开发的开源(BSD许可),开源高性能的高级内存数据结构存储,用作数据库.缓存和消息代理.它支持数据结构,如 字符串.散列.列表.集合,带有范围查询的排序集,位 ...
- springBoot集成Redis遇到的坑(择库)源码分析为什么择库失败
提示: springboot提供了一套链接redis的api,也就是个jar包,用到的连接类叫做LettuceConnectionConfiguration,所以我们引入pom时是这样的 <de ...
- springboot集成redis报错-ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig
当使用Springboot 2.0以上版本集成redis的时候遇到报错信息如下: Application run failed org.springframework.beans.factory.Un ...
- springboot 2.X 集成redis
在实际开发中,经常会引入redis中间件做缓存,这里介绍springboot2.X后如何配置redis 1 Maven中引入redis springboot官方通过spring-boot-autoco ...
随机推荐
- CSS样式简介
层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言.CSS不仅可以静态 ...
- IText实现对PDF文档属性的基本设置
一.Itext简介 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文 ...
- ABP框架系列之三:(Entity Framework Integration-实体框架集成)
ASP.NET Boilerplate can work with any O/RM framework. It has built-in integration with EntityFramewo ...
- vue全局路由守卫beforeEach
在main.js里使用方法 router.beforeEach((to,from,next)=>{}) to,是将要跳转的路由, from,是离开的路由 next是个方法,判断to.path 或 ...
- windows更改命令行cmd的字体为conlosas+微软雅黑
windows更改命令行cmd的字体为conlosas+微软雅黑 动力来源于对美孜孜不倦的追求~ 下载conlosas+微软雅黑字体 谢谢支持. 将解压后的YaHei.Consolas.1.12.tt ...
- Python学习第2章
1.字符串: python中创建字符串我们可以使用引号''或"'. python访问子字符串,可以使用方括号来截取字符串: var="hello world!" var2 ...
- 消息中间件——kafka
1.1.1 什么是消息中间件 消息中间件利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成.通过提供消息传递和消息排队模型,它可以在分布式环境下扩展进程间的通信.对 ...
- 如何在html与delphi间交互代码
[转]如何在html与delphi间交互代码 (2015-11-19 22:16:24) 转载▼ 标签: it 分类: uniGUI uniGUI总群中台中cmj朋友为我们总结了如下内容,对于利用de ...
- nlog 的手动配置
使用nlog的时候,有时候需要手动配置.比如数据库链接和密码不配在文件里,或者统计配置在一个位置之类的. var config = new NLog.Config.LoggingConfigurati ...
- 利用ADO打开Access数据(64位系统)
64位的access一定要用64的程序才能正确打开,仍然用"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Test.accdb;Persist ...