springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce。 此处springboot2.x,所以使用的是Lettuce
关于jedislettuce的区别:

  • Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server。
  • Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
  • Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

新建一个springboot工程,添加如下pom依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- redis依赖commons-pool 这个依赖一定要添加 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

然后在application.yml配置一下redis服务器的地址

server:
port: 1015
spring:
redis:
cache:
nodes: -192.168.159.129:7001
-192.168.159.129:7002
-192.168.159.129:7003
-192.168.159.129:7004
-192.168.159.129:7005
-192.168.159.129:7006
host: localhost:6379
password:
maxIdle:
minIdle:
maxTotal:
maxWaitMillis: 5000

其中nodes为集群redis的参数 host为单机redis的参数

redis配置类:

package webapp.conf;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set; @Configuration
public class RedisConfiguration {
@Value("${spring.redis.cache.nodes:}")
private String nodes;
@Value("${spring.redis.cache.host:}")
private String host;
@Value("${spring.redis.cache.password:}")
private String password;
@Value("${spring.redis.cache.maxIdle:}")
private Integer maxIdle;
@Value("${spring.redis.cache.minIdle:}")
private Integer minIdle;
@Value("${spring.redis.cache.maxTotal:}")
private Integer maxTotal;
@Value("${spring.redis.cache.maxWaitMillis:}")
private Long maxWaitMillis; @Bean
LettuceConnectionFactory lettuceConnectionFactory() {
// 连接池配置
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxIdle(maxIdle == null ? 8 : maxIdle);
poolConfig.setMinIdle(minIdle == null ? 1 : minIdle);
poolConfig.setMaxTotal(maxTotal == null ? 8 : maxTotal);
poolConfig.setMaxWaitMillis(maxWaitMillis == null ? 5000L : maxWaitMillis);
LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
.poolConfig(poolConfig)
.build();
// 单机redis
RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
redisConfig.setHostName(host==null||"".equals(host)?"localhost":host.split(":")[0]);
redisConfig.setPort(Integer.valueOf(host==null||"".equals(host)?"6379":host.split(":")[1]));
if (password != null && !"".equals(password)) {
redisConfig.setPassword(password);
} // 哨兵redis
// RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration(); // 集群redis
/*RedisClusterConfiguration redisConfig = new RedisClusterConfiguration();
Set<RedisNode> nodeses = new HashSet<>();
String[] hostses = nodes.split("-");
for (String h : hostses) {
h = h.replaceAll("\\s", "").replaceAll("\n", "");
if (!"".equals(h)) {
String host = h.split(":")[0];
int port = Integer.valueOf(h.split(":")[1]);
nodeses.add(new RedisNode(host, port));
}
}
redisConfig.setClusterNodes(nodeses);
// 跨集群执行命令时要遵循的最大重定向数量
redisConfig.setMaxRedirects(3);
redisConfig.setPassword(password);*/ return new LettuceConnectionFactory(redisConfig, lettucePoolingClientConfiguration);
} @Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
//序列化类
MyRedisSerializer myRedisSerializer = new MyRedisSerializer();
//key序列化方式
template.setKeySerializer(myRedisSerializer);
//value序列化
template.setValueSerializer(myRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(myRedisSerializer);
return template;
} static class MyRedisSerializer implements RedisSerializer<Object> { @Override
public byte[] serialize(Object o) throws SerializationException {
return serializeObj(o);
} @Override
public Object deserialize(byte[] bytes) throws SerializationException {
return deserializeObj(bytes);
} /**
* 序列化
* @param object
* @return
*/
private static byte[] serializeObj(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
throw new RuntimeException("序列化失败!", e);
}
} /**
* 反序列化
* @param bytes
* @return
*/
private static Object deserializeObj(byte[] bytes) {
if (bytes == null){
return null;
}
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
throw new RuntimeException("反序列化失败!", e);
}
}
}
}

以上已经完成整合教程,测试案例:

注入:

@Autowired
private RedisTemplate<String, Object> redisTemplate;

添加:

redisTemplate.opsForValue().set(key, value);

添加,设置过期时间:

redisTemplate.opsForValue().set(key, obj, expireTime, TimeUnit.SECONDS);

获取:

Object o = redisTemplate.opsForValue().get(key);

删除:

redisTemplate.delete(key);

springboot2.x版本整合redis(单机/集群)(使用lettuce)的更多相关文章

  1. 面向接口编程实现不改代码实现Redis单机/集群之间的切换

    开发中一般使用Redis单机,线上使用Redis集群,因此需要实现单机和集群之间的灵活切换 pom配置: <!-- Redis客户端 --> <dependency> < ...

  2. springboot redis(单机/集群)

    前言 前面redis弄了那么多, 就是为了在项目中使用. 那这里, 就分别来看一下, 单机版和集群版在springboot中的使用吧.  在里面, 我会同时贴出Jedis版, 作为比较. 单机版 1. ...

  3. springboot整合redis(集群)

    一.加入maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...

  4. 【Spring系列】Spring mvc整合redis(非集群)

    一.在pom.xml中增加redis需要的jar包 <!--spring redis相关jar包--> <dependency> <groupId>redis.cl ...

  5. Redis-4.X 版本 Redis Cluster集群 (一)

    一 创建redis cluster 集群前提条件: 1 ) 每个redis node 节点采用相同的硬件配置,相同的密码. 2 ) 每个节点必须开启的参数: cluster-enabled yes # ...

  6. Redis 一二事 - 在spring中使用jedis 连接调试单机redis以及集群redis

    Redis真是好,其中的键值用起来真心强大啊有木有, 之前的文章讲过搭建了redis集群 那么咋们该如何调用单机版的redis以及集群版的redis来使用缓存服务呢? 先讲讲单机版的,单机版redis ...

  7. Redis本地集群搭建(5版本以上)

    Redis本地集群搭建(5版本以上) 2019年11月3日10:05:48 步骤 1.下载安装Redis的安装包 2.复制5份,一共6份Redis的解压安装版,修改每个Redis节点的端口并开启节点 ...

  8. 【精】搭建redis cluster集群,JedisCluster带密码访问【解决当中各种坑】!

    转: [精]搭建redis cluster集群,JedisCluster带密码访问[解决当中各种坑]! 2017年05月09日 00:13:18 冉椿林博客 阅读数:18208  版权声明:本文为博主 ...

  9. Redis Cluster集群搭建与应用

    1.redis-cluster设计 Redis集群搭建的方式有多种,例如使用zookeeper,但从redis 3.0之后版本支持redis-cluster集群,redis-cluster采用无中心结 ...

随机推荐

  1. C Windows控制台字符版本俄罗斯方块

    //一个可以工作在Windows控制台字符界面下的俄罗斯方块 //工作在非图形模式,无需其他库依赖,单个C文件代码即可运行 //支持最高纪录,并且对于纪录进行了加密 //By wrule 2015年1 ...

  2. Chrome中Vim插件cVim

    参考资料:http://blog.csdn.net/hk2291976/article/details/51280816 常用命令: k,w:上移; j,s:下移:h:向左:l:向右:u:上半页d:下 ...

  3. C++学习笔记45:多态性

    运算符重载 运算符是针对新类型数据的实际需要,对原有运算符进行适当的改造 1.比如使复数类的对象可以使用+运算符实现加法: 2.比如使时钟类的对象可以用++运算符实现时间增加1秒: 注意:可以重载为类 ...

  4. sql 索引笔记

    以下资料来自MSDN. 数据库注意事项 设计索引时,应考虑以下数据库准则: 一个表如果建有大量索引会影响 INSERT.UPDATE 和 DELETE 语句的性能,因为在表中的数据更改时,所有索引都须 ...

  5. JAVA自学笔记22

    JAVA自学笔记22 1.操作基本数据类型的流 DataInputStream DataOutputStream 数据输出流允许应用程序以适当方式将基本的Java数据类型写入输出流中.然后,应用程序可 ...

  6. javaScript系列 [02]-javaScript对象探析

    [02]-javaScript对象探析 题记:多年前,以非常偶然的方式关注了微信公众号“面向对象”,本以为这个公众号主要以分享面向对象编程的干货为主,不料其乃实实在在的猿圈相亲平台.通过查看公开资料, ...

  7. python测试开发django-51.Ajax发送post请求登录案例

    前言 我想实现一个登录功能:登录的接口是另外一个地方提供,页面上点登录按钮的时候,先访问登录接口,根据接口返回json信息判断是否登录成功,登录成功页面跳转,登录不成功,在登录首页显示失败原因 登录页 ...

  8. 怎样让两个DIV在同一水平线上面显示

    css定义第二个div. float:right或者left. margin-top:0px 确保第二个DIV的宽度.如果宽度宽的话,会自动到下方的.

  9. docker中的数据库

      注:自从开始使用docker,部署方面的事情就简单多了.使用docker构建的数据库容器不用直接安装,开启后就可以使用,也比以前方便很多.下面将一些要点记录下来. 下面的例子使用以下环境: - 系 ...

  10. 开启win10下Ubuntu子系统的SSH服务 并设置为开机启动

    Win10中安装Ubuntu子系统后默认是没有开启SSH服务的,需要手动配置开启, 1.先通过 bash 进入子系统修改配置 vi /etc/ssh/sshd_config  备注 输入i 表示键入, ...