Redis is a high performance key-value in-memory database. Spring provides official support for Redis. Using Spring Data Redis, you can choose Jedis or Lettuce client. It is easy to operate Redis in Spring Boot projects.
Spring Data Redis is part of the Spring Data family, which provides an abstraction for configuring methods and accessing Redis interfaces. In the underlying implementation, we can choose to use Jedis or Lettuce to access the Redis database.
Jedis and Lettuce are both Redis clients. In short, Jedis is an open source project of the community, and the connection of the database is based on Netty.
This article presents two integration methods, Jedis and Lettuce.
Introduction of depend on
- Add to the pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>{version}</version>
</dependency>
Copy the code
You do not need to specify the version, because in the Spring Boot application, the version information is declared in spring-boot-dependencies, which matches the current Spring Boot version the most. Specifying it yourself manually can cause unexpected compatibility problems.
- If jedis is used, the
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>{version}</version>
</dependency>
Copy the code
- If Luttuce is used, the
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>{version}</version>
</dependency>
Copy the code
The Spring Data Redis 2.3.x version I’m currently using uses Luttuce by default and has dependencies introduced.
configuration
- Add to application.xml
spring:
redis:
host: 127.0. 01. # redis ip
port: 6379 # redis port
password: # redis login password
database: 1 # database
ssl: false
timeout: 2s
Copy the code
This is the general configuration for connecting to Redis. Spring Boot supports configuration of some properties of Jedis or Luttuce. For more information, see Spring Boot Data Properties
use
Create the RedisConnectionFactory factory
- Jedis
@Bean
public JedisConnectionFactory redisConnectionFactory(a) {
return new JedisConnectionFactory(new RedisStandaloneConfiguration());
}
Copy the code
- Luttuce
@Bean
public LettuceConnectionFactory redisConnectionFactory2(a) {
// LettuceConnectionFactory factory = new LettuceConnectionFactory(new RedisSocketConfiguration("/var/run/redis.sock"));
LettuceConnectionFactory factory = new LettuceConnectionFactory(new RedisStandaloneConfiguration());
return factory;
}
Copy the code
There are three Spring Data Redis configuration classes:
/ / a single point of redis RedisStandaloneConfiguration config = new RedisStandaloneConfiguration (); / / the sentinel redis RedisSentinelConfiguration config = new RedisSentinelConfiguration (); / / redis cluster RedisClusterConfiguration config = new RedisClusterConfiguration ();
This article uses a single point of configuration, and the clustering knowledge is presented in Redis
Configuring Cache Management
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
// Set the default timeout for the cache to 30 minutes
redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L));
// If the value is null, it is not cached
redisCacheConfiguration.disableCachingNullValues();
// Set the key serializer
redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
// Set the value serializer
redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
RedisCacheManager.RedisCacheManagerBuilder build = RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory));
RedisCacheManager cacheManager = build.cacheDefaults(redisCacheConfiguration).build();
return cacheManager;
}
Copy the code
After the above configuration, the Spring Boot will automatically assemble and operate the Redis directly with the RedisTemplate
@Autowired
private RedisTemplate redisTemplate;
Copy the code
We can also create our own RedisTemplate object to define how to serialize and deserialize the data store
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
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 uses String serialization
template.setKeySerializer(stringRedisSerializer);
// The hash key also uses String serialization
template.setHashKeySerializer(stringRedisSerializer);
// Value serialization uses Jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// The hash value serialization method uses Jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
Copy the code
RedisTemplate class
RedisTemplate is a class provided in Spring Data Redis to access Redis. Here are some of its common methods:
Boolean hasKey(key) Specifies whether key exists in Redis
Long getExpire(key) Gets the remaining expiration time of the key, returning milliseconds
Boolean delete(key) Delete key
SetOperations opsForSet() Gets a data operation object of type SET
ListOperations opsForList() Gets the list data operation object
ValueOperations opsForValue() Obtains the key value data operation object
HashOperations opsForHash() Retrieves the Map data operation object
See the official API documentation for more methods: RedisTemplate
Distributed lock based on Redis
Distributed locks can be implemented in Redis using setnx and EXPIRE. Here is how it is used:
Set the key value [EX seconds] [PX milliseconds] [NX | XX] EX seconds: set the failure time, PX unit seconds milliseconds: set the failure time, millisecond NX to: XX: set value if key does not exist, return OK on success, return nil on failureCopy the code
Setnx cannot set expire duration at the same time, and cannot guarantee the atomicity of SETnx and EXPIRE. Therefore, a command must be combined when performing distributed locks.
In the API provided by Jedis there is a setNX method, in the RedisTemplate can look like this:
Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, value, 10, TimeUnit.SECONDS);
if(! flag) {/ / has been locked
}
Copy the code
The system uses Redis for caching to greatly improve performance. The use of the Spring cache will be published later.
All are “Siege Lion · Zheng” unless noted. Link to this article: engr-z.com/129.html