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

The method of integrating redis with springboot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points of springboot's method of integrating redis. 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.

1. Pom.xml add dependency

Org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-redis

2. Application-dev.xml configuration

# standalone mode spring: redis: host: 192.168.56.101 # Redis server address database: 0 # Redis database index (default is 0) port: 6379 # Redis server connection port password: redis # Redis server connection password (default is empty) timeout: 300ms # connection timeout (millisecond)

# Sentinel mode

Spring: redis: sentinel: master: mymaster nodes: 192.168.56.101:26379192.168.56.102:26379192.168.56.103:26379 password: redis

3. Java config configuration (single node)

Package com.powertrade.redis.common.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.cache.RedisCacheWriter Import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;/** * Redis standalone configuration * / @ EnableCaching@Configurationpublic class BaseRedisConfig {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisSerializer serializer = redisSerializer () RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setConnectionFactory (redisConnectionFactory); redisTemplate.setKeySerializer (new StringRedisSerializer ()); redisTemplate.setValueSerializer (serializer); redisTemplate.setHashKeySerializer (new StringRedisSerializer ()); redisTemplate.setHashValueSerializer (serializer); redisTemplate.afterPropertiesSet (); return redisTemplate } @ Bean public RedisSerializer redisSerializer () {/ / create JSON serializer Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper objectMapper = new ObjectMapper (); objectMapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); / / must be set, otherwise JSON cannot be converted to an object and will be converted to Map type objectMapper.activateDefaultTyping (LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL) Serializer.setObjectMapper (objectMapper); return serializer;} @ Bean public RedisCacheManager redisCacheManager (RedisConnectionFactory redisConnectionFactory) {RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter (redisConnectionFactory); / / set the validity period of Redis cache to 1 day RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig () .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (redisSerializer () .entryTtl (Duration.ofDays (1)); return new RedisCacheManager (redisCacheWriter, redisCacheConfiguration);}}

4. Sentinel mechanism (multi-node configuration)

Package com.powertrade.redis.common.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;import org.springframework.beans.factory.annotation.Value;import org.springframework.cache.annotation.EnableCaching;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager Import org.springframework.data.redis.cache.RedisCacheWriter;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.RedisNode;import org.springframework.data.redis.connection.RedisPassword;import org.springframework.data.redis.connection.RedisSentinelConfiguration;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer Import java.time.Duration;/** * Redis Sentinel Mechanism configuration * / @ EnableCaching@Configurationpublic class BaseRedisConfig {@ Value ("${spring.redis.sentinel.nodes}") private String redisNodes; @ Value ("${spring.redis.sentinel.master}") private String master; @ Value ("${spring.redis.sentinel.password}") private String password / * redis Sentinel configuration * / @ Bean public RedisSentinelConfiguration redisSentinelConfiguration () {RedisSentinelConfiguration configuration = new RedisSentinelConfiguration (); String [] host = redisNodes.split (","); for (String redisHost: host) {String [] item = redisHost.split (":"); String ip = item [0]; String port = item [1] Configuration.addSentinel (new RedisNode (ip, Integer.parseInt (port));} configuration.setPassword (RedisPassword.of (password)); configuration.setMaster (master); return configuration;} @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisSerializer serializer = redisSerializer (); RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setConnectionFactory (redisConnectionFactory); redisTemplate.setKeySerializer (new StringRedisSerializer ()) RedisTemplate.setValueSerializer (serializer); redisTemplate.setHashKeySerializer (new StringRedisSerializer ()); redisTemplate.setHashValueSerializer (serializer); redisTemplate.afterPropertiesSet (); return redisTemplate;} @ Bean public RedisSerializer redisSerializer () {/ / create JSON serializer Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper objectMapper = new ObjectMapper (); objectMapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) / / must be set, otherwise JSON cannot be converted to an object and will be converted to Map type objectMapper.activateDefaultTyping (LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper (objectMapper); return serializer;} @ Bean public RedisCacheManager redisCacheManager (RedisConnectionFactory redisConnectionFactory) {RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter (redisConnectionFactory) / / set the validity period of Redis cache to 1 day RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig () .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (redisSerializer () .entryTtl (Duration.ofDays (1)); return new RedisCacheManager (redisCacheWriter, redisCacheConfiguration);}}

5. Redis tool class

Package com.powertrade.redis.common.utils;import lombok.RequiredArgsConstructor;import org.springframework.data.redis.core.BoundSetOperations;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit @ Component@RequiredArgsConstructorpublic class RedisCache {public final RedisTemplate redisTemplate; / * cache basic objects, key values of Integer, String, entity classes, etc. * @ param key cache * @ param value cache values * / public void setCacheObject (final String key, final T value) {redisTemplate.opsForValue () .set (key, value) } / * cache basic objects, key values of Integer, String, entity classes, etc. * @ param key cache * @ param value cache value * @ param timeout time * @ param timeUnit time granularity * / public void setCacheObject (final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {redisTemplate.opsForValue (). Set (key, value, timeout, timeUnit) } / * set valid time * * @ param key Redis key * @ param timeout timeout * @ return true= set successfully False= setting failed * / public boolean expire (final String key, final long timeout) {return expire (key, timeout, TimeUnit.SECONDS);} / * * set valid time * * @ param key Redis key * @ param timeout timeout * @ param unit time unit * @ return true= set successfully False= setting failed * / public boolean expire (final String key, final long timeout, final TimeUnit unit) {return redisTemplate.expire (key, timeout, unit);} / * get the cached basic object. * * @ param key cache key value * @ return cache key value corresponding to data * / public T getCacheObject (final String key) {ValueOperations operation = redisTemplate.opsForValue (); return operation.get (key);} / * * Delete a single object * * @ param key * / public boolean deleteObject (final String key) {return redisTemplate.delete (key) } / * * Delete collection objects * * @ param collection multiple objects * @ return * / public long deleteObject (final Collection collection) {return redisTemplate.delete (collection) } / * * cached List data * * @ param key cached key value * @ param dataList List data to be cached * @ return cached object * / public long setCacheList (final String key, final List dataList) {Long count = redisTemplate.opsForList () .rightPushAll (key, dataList); return count = = null? 0: count } / * get the cached list object * * @ param key cached key value * @ return cached key value corresponding to the data * / public List getCacheList (final String key) {return redisTemplate.opsForList () .range (key, 0,-1) } / * * cached Set * * @ param key cache key * @ param dataSet cached data * @ return cached data object * / public BoundSetOperations setCacheSet (final String key, final Set dataSet) {BoundSetOperations setOperation = redisTemplate.boundSetOps (key); Iterator it = dataSet.iterator () While (it.hasNext ()) {setOperation.add (it.next ());} return setOperation;} / * * get the cached set * * @ param key * @ return * / public Set getCacheSet (final String key) {return redisTemplate.opsForSet () .members (key) } / * cache Map * * @ param key * @ param dataMap * / public void setCacheMap (final String key, final Map dataMap) {if (dataMap! = null) {redisTemplate.opsForHash () .putAll (key, dataMap) }} / * get the cached Map * * @ param key * @ return * / public Map getCacheMap (final String key) {return redisTemplate.opsForHash () .entries (key) } / * to store data in Hash * * @ param key Redis key * @ param hKey Hash key * @ param value value * / public void setCacheMapValue (final String key, final String hKey, final T value) {redisTemplate.opsForHash () .put (key, hKey, value) } / * get data in Hash * * @ param key Redis key * @ param hKey Hash key * @ return Hash object * / public T getCacheMapValue (final String key, final String hKey) {HashOperations opsForHash = redisTemplate.opsForHash (); return opsForHash.get (key, hKey) } / * get data in multiple Hash * * @ param key Redis key * @ param hKeys Hash key collection * @ return Hash object collection * / public List getMultiCacheMapValue (final String key, final Collection hKeys) {return redisTemplate.opsForHash () .multiGet (key, hKeys) } / * get the cached basic object list * * @ param pattern string prefix * @ return object list * / public Collection keys (final String pattern) {return redisTemplate.keys (pattern);}} these are all the contents of the article "springboot Integration redis method". 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

Internet Technology

Wechat

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

12
Report