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 connect SpringBoot project to Redis cluster

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to share with you the relevant knowledge points about how to access the SpringBoot project to the Redis cluster. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Configuration parameters

Since this article does not cover the construction of Redis clusters, we assume that we already have a Redis cluster environment, and we need to adjust the following parts of our project

Modify configuration parameters, node and password configuration of the cluster

Make sure that the introduced version of Jedis supports setting passwords. Only passwords can be set above spring-data-redis 1.8 and SpringBoot 1.5 or above.

Inject RedisTemplate

Write tool classes

Modify the configuration parameter # Redis cluster configuration # spring.custome.redis.cluster.nodes=172.20.0.1:7001172.20.0.2:7002172.20.0.3:7003spring.custome.redis.cluster.max-redirects=3spring.custome.redis.cluster.max-active=500spring.custome.redis.cluster.max-wait=-1spring.custome. Redis.cluster.max-idle=500spring.custome.redis.cluster.min-idle=20spring.custome.redis.cluster.timeout=3000spring.custome.redis.cluster.password=redis.cluster.password introduces dependencies (if needed)

Make sure that the version of SpringBoot is greater than 1.4.x, if not, use the following configuration to exclude older versions of Jedis and spring-data-redis from SpringBoot, and then rely on higher versions of Jedis and spring-data-redis.

Org.springframework.boot spring-boot-starter-data-redis redis.clients jedis org.springframework.data spring-data-redis Redis.clients jedis 2.9.0 org.springframework.data spring-data-redis 1.8.0.RELEASE is injected into RedisTemplate

To inject RedisTemplate, we need three components, namely JedisConnectionFactory, RedisClusterConfiguration, and JedisPoolConfig. Here is the code to inject RedisTempalte. First create JedisConnectFactory according to configuration and configure RedisClusterConfiguration and JedisPoolConfig at the same time, and finally return JedisConnectionFactory to create RedisTemplate.

Import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Primary;import org.springframework.data.redis.connection.RedisClusterConfiguration;import org.springframework.data.redis.connection.RedisNode;import org.springframework.data.redis.connection.jedis.JedisClientConfiguration Import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;import java.util.ArrayList;import java.util.List Public class RedisClusterConfig {@ Bean (name = "redisTemplate") @ Primary public RedisTemplate redisClusterTemplate (@ Value ("${spring.custome.redis.cluster.nodes}") String host, @ Value ("${spring.custome.redis.cluster.password}") String password, @ Value ("${spring.custome.redis.cluster.timeout}") long timeout @ Value ("${spring.custome.redis.cluster.max-redirects}") int maxRedirect, @ Value ("${spring.custome.redis.cluster.max-active}") int maxActive, @ Value ("${spring.custome.redis.cluster.max-wait}") int maxWait @ Value ("${spring.custome.redis.cluster.max-idle}") int maxIdle, @ Value ("${spring.custome.redis.cluster.min-idle}") int minIdle) {JedisConnectionFactory connectionFactory = jedisClusterConnectionFactory (host, password, timeout, maxRedirect, maxActive, maxWait, maxIdle, minIdle) Return createRedisClusterTemplate (connectionFactory);} private JedisConnectionFactory jedisClusterConnectionFactory (String host, String password, long timeout, int maxRedirect, int maxActive, int maxWait, int maxIdle, int minIdle) {RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration (); List nodeList = new ArrayList (); String [] cNodes = host.split (",") / / split the cluster node for (String node: cNodes) {String [] hp = node.split (":"); nodeList.add (new RedisNode (hp [0], Integer.parseInt (HP [1]));} redisClusterConfiguration.setClusterNodes (nodeList); redisClusterConfiguration.setPassword (password); redisClusterConfiguration.setMaxRedirects (maxRedirect) / / connection pool general configuration GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig (); genericObjectPoolConfig.setMaxIdle (maxIdle); genericObjectPoolConfig.setMaxTotal (maxActive); genericObjectPoolConfig.setMinIdle (minIdle); genericObjectPoolConfig.setMaxWaitMillis (maxWait); genericObjectPoolConfig.setTestWhileIdle (true); genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis (300000); JedisClientConfiguration.DefaultJedisClientConfigurationBuilder builder = (JedisClientConfiguration.DefaultJedisClientConfigurationBuilder) JedisClientConfiguration .builder () Builder.connectTimeout (Duration.ofSeconds (timeout)); builder.usePooling (); builder.poolConfig (genericObjectPoolConfig); JedisConnectionFactory connectionFactory = new JedisConnectionFactory (redisClusterConfiguration, builder.build ()); / / connection pool initialization connectionFactory.afterPropertiesSet (); return connectionFactory;} private RedisTemplate createRedisClusterTemplate (JedisConnectionFactory redisConnectionFactory) {RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setConnectionFactory (redisConnectionFactory) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper (om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer (); / / key adopts String serialization method redisTemplate.setKeySerializer (stringRedisSerializer) / / key of hash also adopts the serialization method of String redisTemplate.setHashKeySerializer (stringRedisSerializer); / / value serialization uses jackson redisTemplate.setValueSerializer (jackson2JsonRedisSerializer); / / value serialization of hash adopts jackson redisTemplate.setHashValueSerializer (jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet (); return redisTemplate;}} write tool classes

In fact, it is basically completed here. We can see that it is relatively easy for the SpringBoot project to connect to the Redis cluster, and if the stand-alone environment used RedisTemplate before, there is no need to write tool classes now, and the previous operation is still valid.

/ * delete KEY * @ param key * @ return * / public boolean delete (String key) {try {return getTemplate () .delete (key);} catch (Exception e) {log.error ("redis hasKey () is error"); return false }} / * * ordinary cache acquires * * @ param key key * @ return value * / public Object get (String key) {return key = = null? Null: getTemplate (). OpsForValue (). Get (key);} / * * ordinary cache put in * * @ param key key * @ param value value * @ return true success false failed * / public boolean set (String key, Object value) {try {getTemplate () .opsForValue () .set (key, value); return true } catch (Exception e) {log.error ("redis set () is error"); return false }} / * ordinary cache put and set time * * @ param key key * @ param value value * @ param time time (seconds) time is greater than 0 if time is less than or equal to 0, indefinitely * @ return true successful false failed * / public boolean set (String key, Object value) Long time) {try {if (time > 0) {getTemplate () .opsForValue () .set (key, value, time, TimeUnit.SECONDS) } else {set (key, value);} return true;} catch (Exception e) {log.error ("redis set () is error"); return false }} / * counter * * @ param key key * @ return value * / public Long incr (String key) {return getTemplate () .opsForValue () .increment (key);} public Long incrBy (String key, long step) {return getTemplate () .opsForValue () .increment (key, step) } / * * HashGet * * @ param key key cannot be null * @ param item entry cannot be null * @ return value * / public Object hget (String key, String item) {return getTemplate () .opsForHash () .get (key, item) } / * get all key values corresponding to hashKey * * @ param key key * @ return multiple key values * / public Map hmget (String key) {return getTemplate () .opsForHash () .entries (key) } / * obtain the batch key values corresponding to hashKey * @ param key * @ param values * @ return * / public List hmget (String key, List values) {return getTemplate () .opsForHash () .multiGet (key, values);} these are all the contents of the article "how to connect SpringBoot projects to Redis clusters". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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