Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure Lettuce with Redis under SpringBoot2.4.2

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Redis to configure Lettuce under SpringBoot2.4.2". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to configure Lettuce with Redis under SpringBoot2.4.2".

1. Basic integration of Redis under Springboot2.4.2 1.1 maven add dependency org.springframework.boot spring-boot-starter-data-redis 2.4.2

Note: Lettuce is used by default under Springboot2.4.2 instead of Jedis, so there is no need to exclude Jedis from dependencies

1.2 add Redis profile

First of all, Redis needs to prepare a configuration file. This article sets up a separate file redis.properties to be placed under the resource folder.

Redis.properties

HostName = localhost port = 6379 password = password pool.maxIdle = 10000 pool.minIdle = 1000 pool.maxWaitMillis = 5000 pool.maxTotal = 2 database = 101.3 register Bean for RedisTemplate and StringRedisTemplate

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 redisTemplate (LettuceConnectionFactory connectionFactory) {RedisTemplate 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 write a controller example for redis operation 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";}. Add a publisher's interface package com.xxx.demo.redis;/** * @ author linkanyway * @ version 1.0 * @ name MessagePublisher * @ description TODO * @ date on 2022-01-11 23:45 * / public interface MessagePublisher {void publish (final String message);} 2.2 add a publisher's implementation class

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 23:46 on 2022-01-11 * / public class RedisMessagePublisher implements MessagePublisher {@ Autowired private RedisTemplate redisTemplate; @ Autowired private ChannelTopic topic Public RedisMessagePublisher () {} public RedisMessagePublisher (final RedisTemplate redisTemplate, final ChannelTopic topic) {this.redisTemplate = redisTemplate; this.topic = topic;} @ Override public void publish (final String message) {redisTemplate.convertAndSend (topic.getTopic (), message);}} 2.3 add a message listening 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 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 add bean registration

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 23:44 * / @ 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 redisTemplate) {return new RedisMessagePublisher (redisTemplate, topic ());} @ Bean ChannelTopic topic () {return new ChannelTopic ("pubsub:queue");}} 2.5 the controller before rewriting is as follows: 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. Listen for expired events of 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 00:00 on 2022-01-12 * / @ Slf4j@Componentpublic 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 ());}}

Note: Redis needs to enable the event.

Thank you for your reading, the above is the content of "how to configure Lettuce with Redis under SpringBoot2.4.2". After the study of this article, I believe you have a deeper understanding of how to use Redis to configure Lettuce under SpringBoot2.4.2, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report