一、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. 家庭家长本-微信小程序

    寒假在家的时候,做了一个简单的网页版家庭账本,后来自己学习了微信小程序的制作方法,现在想做一个微信小程序的家庭记账本. 首先要在微信公众平台注册一个微信小程序的账号,用的邮箱一个只能注册一个微信小程序 ...

  2. [c#.net]未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件

    问题是这样嘀: 项目采用了三层架构和工厂模式,并借鉴了PetShop的架构,因为这个项目也是采用分布式的数据库,目前只有三个数据库,主要出于提高访问性能考虑. 原来是按照网上对PetShop的介绍来给 ...

  3. java内存性能调优编码注意

    1.没有必要时请不用使用静态变量 使用Java的开发者都知道,当某个对象被定义为stataic变量所引用,这个对象所占有的内存将不会被回收.有时,开发者会将经常调用的对象或者变量定义为static,以 ...

  4. java.security.SecureRandom源码分析 java.security.egd=file:/dev/./urandom

    SecureRandom在java各种组件中使用广泛,可以可靠的产生随机数.但在大量产生随机数的场景下,性能会较低. 这时可以使用"-Djava.security.egd=file:/dev ...

  5. XamlWriter-将对象树写入Xaml

    WPF通常用Xaml格式创建对象树.您还可以使用XamlWriter类进行反方向操作——将对象树写入Xaml. 对于XamlWriter来说,将对象转换成良好的Xaml表示形式通常很容易.但是,您不能 ...

  6. 引用数据类型 Scanner和 Random

    键盘录入Scanner 获取键盘录入的数据,对获取数据的具体操作进行了封装,只需要调用方法,即可得到键盘录入的数据 A:导包            import java.util.Scanner;  ...

  7. DataBrewery Cubes 连接Kylin

    问题背景 Kylin作为一个极其优秀的MOLAP,提供了完整的Cube创建.更新流程.同时提供了Sql查询.功能上看没有问题,但是在提供查询服务的时候还是有些不友好. sql查询需要常常需要关联Hiv ...

  8. Java学习笔记40(缓冲流)

    缓冲流: 在读写文件的各种流中,最令人烦恼的就是效率问题, 而缓冲流的目的就是提高读写效率 字节输出缓冲流: package demo; import java.io.BufferedOutputSt ...

  9. Appium同时连接多台手机进行测试(多线程)

    作为测试小白,当时遇到了N多问题: 开启多线程后,发现app启动后,用例就停止了:且启动app对应的手机不能正确对应,用例中是A手机跑A用例,结果启动了B手机跑A用例报错. 主要原因:Appium S ...

  10. mysql数据表修复

    当数据库表被破坏,运行报错: Table './database/tablename' is marked as crashed and last (automatic?) repair failed ...