一、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的更多相关文章

  1. SpringBoot(十一): Spring Boot集成Redis

    1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...

  2. SpringBoot 2.X以上集成redis

    在网上看到的教程和资料大多数都是2.X以下的版本.使用起来会出现各种问题,通过百度,最后终于弄好了. 2.x以上使用的是 spring-boot-starter-data-redis 2.x一下使用的 ...

  3. SpringBoot集成Redis来实现缓存技术方案

    概述 在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. ...

  4. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  5. 【原创】SpringBoot 2.7.0通过lettuce及commons-pool2 v2.9.0集成Redis踩坑记录

    背景 公司的一个项目由于HTTPS证书到期,导致小程序.POS不能正常使用.所以百度了下,通过URL检测证书有效期的代码,并自行整合到一个服务中. 代码仓库:[基于SpringBoot + 企业微信 ...

  6. Springboot 2.0.x 集成基于Centos7的Redis集群安装及配置

    Redis简介 Redis是一个基于C语言开发的开源(BSD许可),开源高性能的高级内存数据结构存储,用作数据库.缓存和消息代理.它支持数据结构,如 字符串.散列.列表.集合,带有范围查询的排序集,位 ...

  7. springBoot集成Redis遇到的坑(择库)源码分析为什么择库失败

    提示: springboot提供了一套链接redis的api,也就是个jar包,用到的连接类叫做LettuceConnectionConfiguration,所以我们引入pom时是这样的 <de ...

  8. springboot集成redis报错-ClassNotFoundException: org.apache.commons.pool2.impl.GenericObjectPoolConfig

    当使用Springboot 2.0以上版本集成redis的时候遇到报错信息如下: Application run failed org.springframework.beans.factory.Un ...

  9. springboot 2.X 集成redis

    在实际开发中,经常会引入redis中间件做缓存,这里介绍springboot2.X后如何配置redis 1 Maven中引入redis springboot官方通过spring-boot-autoco ...

随机推荐

  1. centos7 安装maven

    进入指定目录 cd /usr/local/src/   下载maven 包 wget http://mirrors.hust.edu.cn/apache/maven/maven-3/3.1.1/bin ...

  2. Linux学习---GCC编译常见错误

    预处理错误: No such file or directory 出错原因:①包含错误:eg  #include <abc.h> //abc.h为用户自行编写文件 解决方法:⑴应改为#in ...

  3. save to project-level dictionary? save to application-level dictionary?

    通过静态代码分析工具lint在Spelling typo得到save to project-level dictionary? save to application-level dictionary ...

  4. 从MATLAB到FPGA 视频和图像处理——讲座学习小结(视频地址https://ww2.mathworks.cn/videos/from-matlab-to-fpga-video-and-image-processing-102492.html)

    1.HDLcoder产品介绍 图像处理分为两个部分: 这里主要讨论第一部分图像处理部分. 一般产品设计流程如下: 适用人群有以下两类: 这里先用一张slider来进行整体概括: 基于模型的设计的好处— ...

  5. PMS构造函数以及apk如何扫描

    一.PackageManagerService构造函数 1.创建data目录下面以及文件(settings的构造函数),然后再添加6个SharedUserSetting 2.开始扫描并且解析APK 3 ...

  6. Java中List, Integer[], int[]的相互转换

    import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Mai ...

  7. Android基础-系统架构分析,环境搭建,下载Android Studio,AndroidDevTools,Git使用教程,Github入门,界面设计介绍

    系统架构分析 Android体系结构 安卓结构有四大层,五个部分,Android分四层为: 应用层(Applications),应用框架层(Application Framework),系统运行层(L ...

  8. Java学习笔记47(JDBC、SQL注入攻击原理以及解决)

    JDBC:java的数据库连接 JDBC本质是一套API,由开发公司定义的类和接口 这里使用mysql驱动,是一套类库,实现了接口 驱动程序类库,实现接口重写方法,由驱动程序操作数据库 JDBC操作步 ...

  9. [译]ElasticSearch vs. Solr

    在Gen2产品的早期阶段, 我们事实上是失败的, 这促使我们重新审视我们现有的技术栈. 我们仔细分析系统中的每个独立的组件,并记录下来, 当然其中也包括构成我们核心功能的搜索引擎技术. 在我们的通用日 ...

  10. Spring Boot定制启动图案

    启动图案 Spring Boot在启动的时候会显示一个默认的Spring的图案,对应的类为SpringBootBanner. . ____ _ __ _ _ /\\ / ___'_ __ _ _(_) ...