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 ...
 
随机推荐
- pyhton 核心编程 正则表达式习题
			
方案一 import re #1. 识别下列字符串:“bat,” “bit,” “but,” “hat,” “hit,” 或 “hut” import re def test1(self): bt = ...
 - VS“新建网站”与“新建Asp.Net Web 应用程序”的区别
			
WebApplication(新建Asp.Net Web 应用程序)编程模型的优点:针对大型网站 1.编译速度网站编译速度快,使用了增量编译模式,仅仅只有文件被修改后,这部分才会被增量编译进去. 2. ...
 - Redis Sentinel 模拟故障迁移
			
什么是redis sentinel 参考文档:https://redis.io/topics/sentinel 简单的来说,就是Redis Sentinel 为redis 提供高可用性,主要体现在下面 ...
 - 其于OpenXml SDK写的帮助类
			
/// <summary> /// 其于OpenXml SDK写的帮助类 /// </summary> public static class OpenXmlHelper { ...
 - bzoj4556(sam)
			
二分答案,(具体可见http://blog.csdn.net/neither_nor/article/details/51669114),然后就是判定问题,sa和sam都可以做,用sam写了一下,先用 ...
 - java技术突破要点
			
一.源码分析 源码分析是一种临界知识,掌握了这种临界知识,能不变应万变,源码分析对于很多人来说很枯燥,生涩难懂. 源码阅读,我觉得最核心有三点:技术基础+强烈的求知欲+耐心. 我认为是阅读源码的最核心 ...
 - Python自动化开发 - MySQL(一)
			
本节内容 一.概述 二.下载安装 三.数据库操作 四.数据表操作 五.表内容操作 一.概述 1.什么是数据库 ? 答:数据的仓库,如:在ATM的示例中我们创建了一个 db 目录,称其为数据库 2.什么 ...
 - Solutions and Summay for Linked List Naive and Easy Questions
			
1.Remove Linked List Elements package linkedlist; /* * Question: Remove all elements from a linked l ...
 - 【转】UniGUI Session管理說明
			
[转]UniGUI Session管理說明 (2015-12-29 15:41:15) 转载▼ 分类: uniGUI 台中cmj朋友在uniGUI中文社区QQ群里发布的,转贴至此. UniGUI ...
 - NET Core微服务之路:再谈分布式系统中一致性问题分析
			
前言 一致性:很多时候表现在IT系统中,通常在分布式系统中,必须(或最终)为多个节点的数据保持一致.世间万物,也有存在相同的特征或相似,比如儿时的双胞胎,一批工厂流水线的产品,当然,我们不去讨论非IT ...