SpringBoot2.4.2下使用Redis配置Lettuce的示例

目录
  • 1. Springboot2.4.2下对Redis的基础集成
    • 1.1 maven添加依赖
    • 1.2 添加Redis配置文件
    • 1.3 注册RedisTemplate和StringRedisTemplate的Bean
    • 1.4 编写一个控制器示例进行redis操作
  • 2. 使用redis进行发布订阅
    • 2.1 添加一个发布者的接口
    • 2.2 添加一个发布者的实现类
    • 2.3 添加一个消息监听bean
    • 2.4 添加bean注册
    • 2.5 改写之前的控制器如下
  • 3. 监听key的过期事件

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下使用Redis配置Lettuce的文章就介绍到这了,更多相关SpringBoot配置Lettuce内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot集成redis lettuce

    目前java操作redis的客户端有jedis跟Lettuce.在springboot1.x系列中,其中使用的是jedis,但是到了springboot2.x其中使用的是Lettuce. 因为我们的版本是springboot2.x系列,所以今天使用的是Lettuce. 关于jedis跟lettuce的区别: Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server. Jedis在实现上是直接连接的redis server,如果在多线程环

  • springboot redis使用lettuce配置多数据源的实现

    目前项目上需要连接两个redis数据源,一个redis数据源是单机模式,一个redis数据源是分片集群模式,这里将具体配置列一下. 项目用的springboot版本为 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</ver

  • 关于SpringBoot整合redis使用Lettuce客户端超时问题

    参考的博客 问题起因 做毕设的时候,使用到Lettuce连接redis,一段时间后不操作,再去操作redis,会报连接超时错误,在其重连后又可使用. 原因是:Lettuce 自适应拓扑刷新(Adaptive updates)与定时拓扑刷新(Periodic updates) 是默认关闭的导致问题的出现 解决的方案 1.重写连接工厂实例,更改其LettuceClientConfiguration 为开启拓扑更新 @Configuration public class RedisConfig { @

  • SpringBoot2.4.2下使用Redis配置Lettuce的示例

    目录 1. Springboot2.4.2下对Redis的基础集成 1.1 maven添加依赖 1.2 添加Redis配置文件 1.3 注册RedisTemplate和StringRedisTemplate的Bean 1.4 编写一个控制器示例进行redis操作 2. 使用redis进行发布订阅 2.1 添加一个发布者的接口 2.2 添加一个发布者的实现类 2.3 添加一个消息监听bean 2.4 添加bean注册 2.5 改写之前的控制器如下 3. 监听key的过期事件 1. Springbo

  • springboot2整合redis使用lettuce连接池的方法(解决lettuce连接池无效问题)

    lettuce客户端 Lettuce 和 Jedis 的都是连接Redis Server的客户端程序.Jedis在实现上是直连redis server,多线程环境下非线程安全(即多个线程对一个连接实例操作,是线程不安全的),除非使用连接池,为每个Jedis实例增加物理连接.Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问(即多个线程公用一个连接实例,线程安全),同时它是可伸缩的设计,一个连接

  • CentOS 7下安装 redis 3.0.6并配置集群的过程详解

    安装依赖 [root@centos7-1 ~]# yum -y install gcc openssl-devel libyaml-devel libffi-devel readline-devel zlib-devel gdbm-devel ncurses-devel gcc-c++ automake autoconf 安装 redis [root@centos7-1 ~]# wget http://download.redis.io/releases/redis-3.0.6.tar.gz [

  • Redis 对比 Memcached 并在 CentOS 下进行安装配置详解

    Redis 是一个开源.支持网络.基于内存.键值对的 Key-Value 数据库,本篇文章主要介绍了Redis 对比 Memcached 并在 CentOS 下进行安装配置详解,有兴趣的可以了解一下. 了解一下 Redis Redis 是一个开源.支持网络.基于内存.键值对的 Key-Value 数据库,使用 ANSI C 编写,并提供多种语言的 API ,它几乎没有上手难度,只需要几分钟我们就能完成安装工作,并让它开始与应用程序顺畅协作.换句话来说,只需投入一小部分时间与精力,大家就能获得立竿

  • CentOS6.5下Tomcat7 Nginx Redis配置步骤教程详解

    所有配置均在一台机器上完成,部署拓扑信息如下: 注意:由于Redis配置对jar包和tomcat版本比较严格,请务必使用tomcat7和本文中提供的jar包. 下载地址: http://pan.baidu.com/s/1bO67Ky tomcat: tomcat1 localhost:8080 tomcat2 localhost:9080 nginx: localhost:1210 redis: localhost:6379 1. tomcat的安装和配置 1. 在server.xml文件中,修

  • redis 使用lettuce 启动内存泄漏错误的解决方案

    redis 使用 lettuce 出现 LEAK: hashedwheelTimer.release() was not called before it's garbage-collected. Enable advanced leak 内存泄漏.其实是内存不够大导致. 找到eclispe 中window->preferences->Java->Installed JRE ,点击右侧的Edit 按钮,在编辑界面中的 "Default VM Arguments "选项

  • 图文详解Windows下使用Redis缓存工具的方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). 这些数据类型都支持push/pop.add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的.在此基础上,redis支持各种不同方式的排序.与memcached一样,为了保证效率,数据都是缓存在内存中.区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记

  • Windows下安装Redis及使用Python操作Redis的方法

    首先说一下在Windows下安装Redis,安装包可以在https://github.com/MSOpenTech/redis/releases中找到,可以下载msi安装文件,也可以下载zip的压缩文件. 下载zip文件之后解压,解压后是这些文件: 里面这个Windows Service Documentation.docx是一个文档,里面有安装指导和使用方法. 也可以直接下载msi安装文件,直接安装,安装之后的安装目录中也是这些文件,可以对redis进行相关的配置. 安装完成之后可以对redi

随机推荐