一、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. JS判断是否有js、css文件的引入方法

    在页面头部有个 <script type="text/javascript" src="abc.js"></script> <li ...

  2. ABP框架系列之十一:(AspNet-Core-ASPNET核心)

    Introduction This document describes ASP.NET Core integration for ASP.NET Boilerplate framework. ASP ...

  3. redis 集群模式安装

    概念 Redis集群提供一种方式自动将数据分布在多个Redis节点上. 每个Redis集群中的节点都需要打开两个TCP连接.一个连接用于正常的给Client提供服务,比如6379,还有一个额外的端口( ...

  4. Jersey RESTful WebService框架学习(八)文件下载防乱码

    最近在做下载时候  不同浏览器下载的文件一直出现乱码,不知道怎么设置文件的编码,百度许久,找到一个解决办法如下 /** * 文件下载 * @param request * @return */ @GE ...

  5. Maths | 二次型求偏导

  6. jdk8中关于操作集合的一些新特性,遍历和排序操作

    jdk8增加了不少新的东西,在集合操作这块,就有如 lamda表达式,stream,sort,optional等新的类,主要涉及遍历和排序等方面,新特性提升了不少性能,我们开发就是要拥抱新事物,守着老 ...

  7. kali安装配置ftp

    参考:https://zhidao.baidu.com/question/1511146077646448900.html 一)安装 1.用sudo apt-get install 下载安装包

  8. day15_雷神_前端03

    # 前端 day03 内容回顾 javascript: 1.ECMAScript5.0 es6(阮一峰) es7 es8 (1)声明变量 var let (2)内置函数 Date Math.rando ...

  9. day_1 Python介绍及计算机组成和系统

    python学习路线 基础语法 - 文件操作 - 函数 - 模块 - 面向对象(类) - 网络编程 - 数据库 - 前段 - 项目 学习方法 wwwh: what-why-where-how #wha ...

  10. tar与压缩详解

    .gz  gzip   gunzip(gzip -d) .zip .rar .bz2 gzip压缩文件不保留原文件 , 不能压缩目录 gzip   filename.x   用gzip压缩文件 gun ...