1. Springboot2.4.2下对Redis的基础集成

1.1 maven添加依赖

    <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.2</version>
</dependency>

注:Springboot2.4.2下默认使用的就是Lettuce而不是Jedis因此无需在依赖进行排除Jedis

1.2 添加Redis配置文件

首先Redis需要准备一个配置文件,本文设定一个单独的文件redis.properties 放在resource文件夹下

redis.properties

  hostName = localhost
port = 6379
password = password
pool.maxIdle = 10000
pool.minIdle = 1000
pool.maxWaitMillis = 5000
pool.maxTotal = 2
database = 10

1.3 注册RedisTemplate和StringRedisTemplate的Bean

LettuceRedisConfig.java

package com.xxx.demo.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.Serializable;
import java.time.Duration; /**
* @author linkanyway
* @version 1.0
* @name LettuceRedisConfig
* @description TODO
* @date 2022/01/11 22:44
*/
@Configuration
@PropertySource("classpath:redis.properties")
public class LettuceRedisConfig { @Value("${hostName}")
private String hostName; @Value("${password}")
private String password;
@Value("${port}")
private int port; @Value("${database}")
private int database; @Value("${pool.maxIdle}")
private int maxIdle; @Value("${pool.minIdle}")
private int minIdle; @Value("${pool.maxWaitMillis}")
private int maxWaitMillis; @Value("${pool.maxTotal}")
private int maxTotal; /**
* LettuceConnectionFactory
*
* @return
*/
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
redisStandaloneConfiguration.setHostName (hostName);
redisStandaloneConfiguration.setPort (port);
redisStandaloneConfiguration.setPassword (password);
redisStandaloneConfiguration.setDatabase (database); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig ();
poolConfig.setMaxIdle (maxIdle);
poolConfig.setMinIdle (minIdle);
poolConfig.setMaxWaitMillis (maxWaitMillis);
poolConfig.setMaxTotal (maxTotal); LettucePoolingClientConfiguration lettucePoolingClientConfiguration =
LettucePoolingClientConfiguration.builder ().commandTimeout (Duration.ofSeconds (10)).shutdownTimeout (Duration.ZERO).poolConfig (poolConfig).build (); LettuceConnectionFactory lettuceConnectionFactory =
new LettuceConnectionFactory (redisStandaloneConfiguration, lettucePoolingClientConfiguration);
lettuceConnectionFactory.setShareNativeConnection (false); return lettuceConnectionFactory;
} /**
* RedisTemplate
*
* @param connectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<> ();
redisTemplate.setKeySerializer (new StringRedisSerializer ());
redisTemplate.setValueSerializer (new GenericJackson2JsonRedisSerializer ());
redisTemplate.setConnectionFactory (connectionFactory);
return redisTemplate;
} /**
* @param factory
* @return
*/
@Bean
public StringRedisTemplate configStringRedisTemplate(@Autowired LettuceConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate (factory);
template.setEnableTransactionSupport (true);
ObjectMapper mapper;
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer ();
template.setValueSerializer (new StringRedisSerializer ());
template.setKeySerializer (new StringRedisSerializer ());
template.setHashKeySerializer (new StringRedisSerializer ());
template.setHashValueSerializer (new StringRedisSerializer ());
template.afterPropertiesSet ();
return template;
} }

1.4 编写一个控制器示例进行redis操作

package com.xx.demo.controller;

import com.xxx.demo.redis.MessagePublisher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @author linkanyway
* @version 1.0
* @name RedisController
* @description TODO
* @date 2022/01/11 22:37
*/
@RestController
@RequestMapping("redis")
public class RedisController { final
StringRedisTemplate redisTemplate; public RedisController(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate; } @GetMapping("add")
public String add() {
redisTemplate.opsForValue ().set ("a", "1");
return "hi";
} }

2. 使用redis进行发布订阅

2.1 添加一个发布者的接口

package com.xxx.demo.redis;

/**
* @author linkanyway
* @version 1.0
* @name MessagePublisher
* @description TODO
* @date 2022/01/11 23:45
*/
public interface MessagePublisher {
void publish(final String message);
}

2.2 添加一个发布者的实现类

RedisMessagePublisher.java

package com.xxx.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic; import java.io.Serializable; /**
* @author linkanyway
* @version 1.0
* @name RedisMessagePublisher
* @description TODO
* @date 2022/01/11 23:46
*/
public class RedisMessagePublisher implements MessagePublisher { @Autowired
private RedisTemplate<String, Serializable> redisTemplate;
@Autowired
private ChannelTopic topic; public RedisMessagePublisher() {
} public RedisMessagePublisher(final RedisTemplate<String, Serializable> redisTemplate, final ChannelTopic topic) {
this.redisTemplate = redisTemplate;
this.topic = topic;
} @Override
public void publish(final String message) {
redisTemplate.convertAndSend (topic.getTopic (), message);
}
}

2.3 添加一个消息监听bean

RedisMessageSubscriber.java

package com.xxx.demo.redis;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.scheduling.annotation.Async; /**
* @author linkanyway
* @version 1.0
* @name RedisMessageSubscriber
* @description TODO
* @date 2022/01/11 23:47
*/
public class RedisMessageSubscriber implements MessageListener {
@Override
@Async
public void onMessage(Message message, byte[] pattern) {
System.out.println ("Message received: " + new String (message.getBody ()));
}
}

2.4 添加bean注册

RedisMessageConfig.java

package com.xxx.demo.redis;

import org.springframework.beans.factory.annotation.Autowired;
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.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import java.io.Serializable; /**
* @author linkanyway
* @version 1.0
* @name RedisMessageConfig
* @description TODO
* @date 2022/01/11 23:44
*/
@Configuration
public class RedisMessageConfig { @Bean
MessageListenerAdapter messageListener() {
return new MessageListenerAdapter (new RedisMessageSubscriber ());
} @Bean
RedisMessageListenerContainer redisContainer(LettuceConnectionFactory factory) {
final RedisMessageListenerContainer container = new RedisMessageListenerContainer ();
container.setConnectionFactory (factory);
container.addMessageListener (messageListener (), topic ());
return container;
} @Bean
MessagePublisher redisPublisher(@Autowired RedisTemplate<String, Serializable> redisTemplate) {
return new RedisMessagePublisher (redisTemplate, topic ());
} @Bean
ChannelTopic topic() {
return new ChannelTopic ("pubsub:queue");
}
}

2.5 改写之前的控制器如下

package com.xxx.demo.controller;

import com.kreakin.demo.redis.MessagePublisher;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @author linkanyway
* @version 1.0
* @name RedisController
* @description TODO
* @date 2022/01/11 22:37
*/
@RestController
@RequestMapping("redis")
public class RedisController { final
StringRedisTemplate redisTemplate;
final
MessagePublisher publisher; public RedisController(StringRedisTemplate redisTemplate, MessagePublisher publisher) {
this.redisTemplate = redisTemplate;
this.publisher = publisher;
} @GetMapping("hi")
public String hi() {
redisTemplate.opsForValue ().set ("a", "1");
return "hi";
} @GetMapping("pub")
public String pub() {
publisher.publish ("sdfsf");
return "ok";
}
}

3. 监听key的过期事件

RedisKeyExpireSubscriber.java

package com.xxx.demo.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component; /**
* @author linkanyway
* @version 1.0
* @name RedisKeyExpireSubscriber
* @description TODO
* @date 2022/01/12 00:00
*/
@Slf4j
@Component
public class RedisKeyExpireSubscriber extends KeyExpirationEventMessageListener {
/**
* Creates new {@link } for {@code __keyevent@*__:expired} messages.
*
* @param listenerContainer must not be {@literal null}.
*/
public RedisKeyExpireSubscriber(RedisMessageListenerContainer listenerContainer) {
super (listenerContainer);
} @Override
public void onMessage(Message message, byte[] pattern) {
log.error (message.toString ());
}
}

注意: Redis需要开启事件

SpringBoot2.4.2下配置Lettuce使用Redis的更多相关文章

  1. windows环境下配置php和redis

    Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. 一.Window 下安装 下载地址:https://github.com/dmajkic/redis/downl ...

  2. SpringBoot(十一):springboot2.0.2下配置mybatis generator环境,并自定义字段/getter/settetr注释

    Mybatis Generator是供开发者在mybatis开发时,快速构建mapper xml,mapper类,model类的一个插件工具.它相对来说对开发者是有很大的帮助的,但是它也有不足之处,比 ...

  3. Ubuntu下PHP开发配置(新增redis、sphinx、sqlserver相关配置)

    由于本人比较懒,所以一般都是用xampp的直接拿来改的…………(当然xampp中一般php版本都是比较新的用的过程中请大家注意哈,可能会和老版本冲突) 此次除了使用xampp外,还扩展了sphinx, ...

  4. Linux下配置Redis集群模式

    配置机器1 在演示中,172.16.179.130为当前ubuntu机器的ip 在172.16.179.130上进⼊Desktop⽬录,创建conf⽬录 在conf⽬录下创建⽂件7000.conf,编 ...

  5. windows下配置redis集群,启动节点报错:createing server TCP listening socket *:7000:listen:Unknown error

    windows下配置redis集群,启动节点报错:createing server TCP listening socket *:7000:listen:Unknown error 学习了:https ...

  6. Windows下配置Redis,并修改密码

    原文:Windows下配置Redis,并修改密码 Windows下配置Redis,并修改密码 下载 Redis Windows版本的GitHub链接,直接下载zip文件解压到指定文件夹下或者下载msi ...

  7. Ubuntu下配置python完成爬虫任务(笔记一)

    Ubuntu下配置python完成爬虫任务(笔记一) 目标: 作为一个.NET汪,是时候去学习一下Linux下的操作了.为此选择了python来边学习Linux,边学python,熟能生巧嘛. 前期目 ...

  8. linux安装和配置 mysql、redis 过程中遇到的问题记录

    linux下部署mysql和redis网上的教程很多,这里记录一下我部署.配置的过程中遇到的一些问题和解决办法. mysql ①安装完成后启动的时候报错 Starting MySQL.The serv ...

  9. redis的单实例配置+web链接redis

    [root@cache01 src]# wget http://download.redis.io/redis-stable.tar.gz [root@cache01 src]# tar -xzvf ...

随机推荐

  1. 减轻内存负担,在 pymysql 中使用 SSCursor 查询结果集较大的 SQL

    前言 默认情况下,使用 pymysql 查询数据使用的游标类是 Cursor,比如: import pymysql.cursors # 连接数据库 connection = pymysql.conne ...

  2. CF749B Parallelogram is Back 题解

    Content 给出平行四边形的三个顶点 \((x_1,y_1),(x_2,y_2),(x_3,y_3)\),求出所有可能的第四个顶点. 数据范围:\(\forall i\in[1,3],-1000\ ...

  3. UVA11951 Area 题解

    Content 小 S 想买下一块地.他所在的城市可以看成一个 \(n\times m\) 的网格,要购买所处在 \((i,j)\) 的网格需要缴税 \(c_{i,j}\) 元,如果一块地里面有多个网 ...

  4. 贪心——122.买卖股票的最佳时机II

    给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. 设计一个算法来计算你所能获取的最大利润.你可以尽可能地完成更多的交易(多次买卖一支股票). 注意:你不能同时参与多笔交易(你必须在再次 ...

  5. Sharepoint 列表分页开发

    虽然现在linq技术对列表操作都是对实体操作了,但是linq有一点不好,那就是分页舞从下手,假如查出满足条件的记录有1万条,而在分页的时候我每次只需要显示10条,那么我每次点击下一页的时候都查询的是1 ...

  6. C# 使用Fluent API 创建自己的DSL

    DSL(Domain Specified Language)领域专用语言是描述特定领域问题的语言,听起来很唬人,其实不是什么高深的东西.看一下下面的代码: using FlunetApiDemo; v ...

  7. 【LeetCode】541. Reverse String II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  8. 【LeetCode】747. Largest Number At Least Twice of Others 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 寻找两次最大值 排序 大顶堆 日期 题目地址:htt ...

  9. Cornfields(poj2019)

    Cornfields Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 6798   Accepted: 3315 Descri ...

  10. 来自Java程序员的Python新手入门小结

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...