iis服务器助手广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot2.4.2下怎么使用Redis配置Lettuce
  • 665
分享到

SpringBoot2.4.2下怎么使用Redis配置Lettuce

2023-06-26 05:06:47 665人浏览 八月长安
摘要

这篇文章主要讲解了“SpringBoot2.4.2下怎么使用Redis配置Lettuce”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“springBoot2.4.2下怎么使用Redis配置L

这篇文章主要讲解了“SpringBoot2.4.2下怎么使用Redis配置Lettuce”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“springBoot2.4.2下怎么使用Redis配置Lettuce”吧!

    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;@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;        @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;    }        @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;    }        @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;@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;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;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;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;@Configurationpublic 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;@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;@Slf4j@Componentpublic class RedisKeyExpireSubscriber extends KeyExpirationEventMessageListener {        public RedisKeyExpireSubscriber(RedisMessageListenerContainer listenerContainer) {        super (listenerContainer);    }    @Override    public void onMessage(Message message, byte[] pattern) {        log.error (message.toString ());    }}

    注意: Redis需要开启事件

    感谢各位的阅读,以上就是“SpringBoot2.4.2下怎么使用Redis配置Lettuce”的内容了,经过本文的学习后,相信大家对SpringBoot2.4.2下怎么使用Redis配置Lettuce这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

    --结束END--

    本文标题: SpringBoot2.4.2下怎么使用Redis配置Lettuce

    本文链接: https://www.lsjlt.com/news/307018.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    • SpringBoot2.4.2下怎么使用Redis配置Lettuce
      这篇文章主要讲解了“SpringBoot2.4.2下怎么使用Redis配置Lettuce”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot2.4.2下怎么使用Redis配置L...
      99+
      2023-06-26
    • SpringBoot2.4.2下使用Redis配置Lettuce的示例
      目录1. Springboot2.4.2下对Redis的基础集成1.1 maven添加依赖1.2 添加Redis配置文件1.3 注册RedisTemplate和StringRedis...
      99+
      2024-04-02
    • Redis之Lettuce怎么使用
      本篇内容主要讲解“Redis之Lettuce怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Redis之Lettuce怎么使用”吧!一、摘要Lettuce 是 Redis 的一款高级 Ja...
      99+
      2023-07-04
    • springboot redis如何使用lettuce配置多数据源
      这篇文章将为大家详细讲解有关springboot redis如何使用lettuce配置多数据源,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。springboot是什么springboot一种全新的编程规范...
      99+
      2023-06-14
    • springboot redis使用lettuce配置多数据源的实现
      目前项目上需要连接两个redis数据源,一个redis数据源是单机模式,一个redis数据源是分片集群模式,这里将具体配置列一下。 项目用的springboot版本为 &...
      99+
      2024-04-02
    • SpringBoot和redis中怎么使用Lettuce客户端
      这篇文章给大家介绍SpringBoot和redis中怎么使用Lettuce客户端,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。重写连接工厂实例,更改其LettuceClientConfiguration 为开启拓扑更新...
      99+
      2023-06-20
    • 怎么配置使用redis
      本篇内容主要讲解“怎么配置使用redis”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么配置使用redis”吧!Spring-data-redis为spring-data模块中对redis的支...
      99+
      2023-06-04
    • Jmeter怎么下载配置使用
      本篇内容介绍了“Jmeter怎么下载配置使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!jemter简介jmeter是apache公司基于...
      99+
      2023-06-21
    • Redis哨兵模式怎么配置和使用
      Redis哨兵模式是一种用于监控和管理Redis主从复制和高可用性的机制。当主服务器出现故障时,哨兵可以自动将从服务器升级为主服务器...
      99+
      2024-05-07
      Redis
    • Redis主从复制怎么配置和使用
      在Redis中,主从复制是一种常用的数据备份和负载均衡技术。主从复制可以让一个Redis服务器(称为主节点)将数据复制到其他Redi...
      99+
      2024-05-07
      Redis
    • Docker下Redis集群安装配置怎么实现
      这篇文章主要介绍“Docker下Redis集群安装配置怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Docker下Redis集群安装配置怎么实现”文章能帮助大家解决问题。一、所有机器拉去镜像...
      99+
      2023-07-02
    • Redis慢查询日志怎么配置和使用
      Redis慢查询日志可以通过配置redis.conf文件来开启和配置,具体步骤如下: 打开redis.conf文件,在其中添加如下...
      99+
      2024-05-07
      Redis
    • Thinkphp6中配置并使用redis
      目录 一、安装redis 二、在thinkphp6中配置redis 三、在TP6框架中简单使用redis   四、总结 一、安装redis ThinkPHP内置支持的缓存类型包括file、memcache、wincache、sqlit...
      99+
      2023-09-01
      redis 缓存 数据库 1024程序员节 php
    • redis怎么重启配置
      非常抱歉,由于您没有提供文章标题,我无法为您生成一篇高质量的文章。请您提供文章标题,我将尽快为您生成一篇优质的文章。...
      99+
      2024-05-21
    • redis怎么读取配置
      非常抱歉,由于您没有提供文章标题,我无法为您生成一篇高质量的文章。请您提供文章标题,我将尽快为您生成一篇优质的文章。...
      99+
      2024-05-21
    • Redis的键空间通知怎么配置和使用
      在Redis中,可以使用键空间通知来监控数据库中键的变化。要配置和使用键空间通知,可以按照以下步骤进行: 配置Redis服务器以...
      99+
      2024-05-07
      Redis
    • redis和mysql搭配怎么使用
      redis 和 mysql 搭配使用可以发挥各自的优势:redis:高速读写,适用于缓存、队列处理。mysql:持久化存储,适用于需要持久化、查询关系的数据。搭配使用场景:缓存、队列处理...
      99+
      2024-04-02
    • redis和mysql怎么配合使用
      Redis和MySQL可以通过以下几种方式配合使用:1. 缓存查询结果:将MySQL的查询结果存储到Redis中,当下次需要同样的查...
      99+
      2023-08-18
      redis mysql
    • Java使用Lettuce客户端在Redis在主从复制模式下命令执行的操作
      1 redis主从复制的概念 多机环境下,一个redis服务接收写命令,当自身数据与状态发生变化,将其复制到一个或多个redis。这种模式称为主从复制。在redis中通过命令salv...
      99+
      2024-04-02
    • redis配置文件怎么找
      redis配置文件怎么找?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!Redis的配置文件位于Redis安装目录下,文件名...
      99+
      2024-04-02
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作