欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年01月13日 15:42:06   作者:linkanyway  
這篇文章主要介紹了SpringBoot2.4.2下使用Redis配置Lettuce,Springboot2.4.2下默認(rèn)使用的就是Lettuce而不是Jedis因此無需在依賴進(jìn)行排除Jedis,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

1. Springboot2.4.2下對(duì)Redis的基礎(chǔ)集成

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下默認(rèn)使用的就是Lettuce而不是Jedis因此無需在依賴進(jìn)行排除Jedis

1.2 添加Redis配置文件

首先Redis需要準(zhǔn)備一個(gè)配置文件,本文設(shè)定一個(gè)單獨(dú)的文件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 注冊(cè)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 編寫一個(gè)控制器示例進(jìn)行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進(jìn)行發(fā)布訂閱

2.1 添加一個(gè)發(fā)布者的接口

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 添加一個(gè)發(fā)布者的實(shí)現(xiàn)類

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 添加一個(gè)消息監(jiān)聽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注冊(cè)

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. 監(jiān)聽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需要開啟事件

到此這篇關(guān)于SpringBoot2.4.2下使用Redis配置Lettuce的文章就介紹到這了,更多相關(guān)SpringBoot配置Lettuce內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解java平臺(tái)解析協(xié)議相關(guān)備忘

    詳解java平臺(tái)解析協(xié)議相關(guān)備忘

    這篇文章主要介紹了詳解java平臺(tái)解析協(xié)議相關(guān)備忘,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • Java策略模式取代if else

    Java策略模式取代if else

    在策略模式(Strategy Pattern)中,一個(gè)類的行為或其算法可以在運(yùn)行時(shí)更改。這種類型的設(shè)計(jì)模式屬于行為型模式。在策略模式中,我們創(chuàng)建表示各種策略的對(duì)象和一個(gè)行為隨著策略對(duì)象改變而改變的 context 對(duì)象。策略對(duì)象改變 context 對(duì)象的執(zhí)行算法
    2021-10-10
  • springboot中server.ssl.key-store配置路徑的問題小結(jié)

    springboot中server.ssl.key-store配置路徑的問題小結(jié)

    這篇文章主要介紹了springboot中server.ssl.key-store配置路徑的問題,文中還記錄了Spring Boot SSL(https)實(shí)例,介紹在web程序中使用自簽名的SSL(HTTPS)證書及創(chuàng)建SSL認(rèn)證,感興趣的朋友跟隨小編一起看看吧
    2024-02-02
  • StreamAPI多次消費(fèi)一個(gè)stream代碼實(shí)例

    StreamAPI多次消費(fèi)一個(gè)stream代碼實(shí)例

    這篇文章主要介紹了StreamAPI多次消費(fèi)一個(gè)stream代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • 出現(xiàn)java.lang.NoSuchMethodException異常的解決(靠譜)

    出現(xiàn)java.lang.NoSuchMethodException異常的解決(靠譜)

    這篇文章主要介紹了出現(xiàn)java.lang.NoSuchMethodException異常的解決方案(靠譜),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • java策略枚舉:消除在項(xiàng)目里大批量使用if-else的優(yōu)雅姿勢(shì)

    java策略枚舉:消除在項(xiàng)目里大批量使用if-else的優(yōu)雅姿勢(shì)

    這篇文章主要給大家介紹了關(guān)于Java徹底消滅if-else的8種方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2021-06-06
  • SpringMVC中@ModelAttribute注解的使用教程

    SpringMVC中@ModelAttribute注解的使用教程

    在SpringMVC中,我們可以通過使用@ModelAttribute注解標(biāo)記方法,實(shí)現(xiàn)類似于Struts2中Preparable攔截器的效果,這篇文章主要給大家介紹了關(guān)于SpringMVC中@ModelAttribute注解使用的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • Mybatis懶加載的實(shí)現(xiàn)

    Mybatis懶加載的實(shí)現(xiàn)

    這篇文章主要介紹了Mybatis懶加載的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Java實(shí)現(xiàn)的生成二維碼和解析二維碼URL操作示例

    Java實(shí)現(xiàn)的生成二維碼和解析二維碼URL操作示例

    這篇文章主要介紹了Java實(shí)現(xiàn)的生成二維碼和解析二維碼URL操作,結(jié)合實(shí)例形式分析了Java創(chuàng)建與解析二維碼,以及文件讀寫等相關(guān)操作技巧,需要的朋友可以參考下
    2018-07-07
  • Spring Boot中@ConditionalOnProperty的使用方法

    Spring Boot中@ConditionalOnProperty的使用方法

    這篇文章主要給大家介紹了關(guān)于Spring Boot中@ConditionalOnProperty的使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12

最新評(píng)論