Introduction of Redis

What is a Redis

Redis is a very widely used free open source in-memory database, is a high performance key-value database.

Redis has three characteristics compared to other key-value caches, such as Memcached:

1.Redis supports data persistence. It can save the data in memory to disk, which can be loaded again for use upon restart. 2.Redis not only supports simple key-value type data, but also provides the storage of list, set, zset, hash and other data structures. 3.Redis supports data backup, that is, data backup in master-slave mode.

Redis has the following advantages:

1. High performance. Redis can read 110,000 times per second and write 81,000 times per second. 2. Rich data types. Redis supports Strings, Lists, Sets and Ordered Sets data types for binary cases. 3. Atomicity. All operations in Redis are atomic, meaning that they are either executed on success or not executed at all. Individual operations are atomic, as are multiple operations, held together by MULTI and EXEC instructions. 4. Rich features. Redis also supports publish/subscribe, notification, and key expiration features.

Spring Boot integrates Redis

1. Add dependencies to the project

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.9. RELEASE</version>
		<relativePath /> <! -- lookup parent from repository -->
	</parent>
	<groupId>cn.zwqh</groupId>
	<artifactId>spring-boot-redis</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>spring-boot-redis</name>
	<description>spring-boot-redis</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<! -- Redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
	
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Copy the code

See the jar package found that Spring Data under the Redis org. Springframework. Data. Redis. The connection path below the default, there are two packages in jedis and lettuce, This means that Spring Boot has already wrapped both Redis clients by default.

In SpringBoot 1.5.x, the default Redis client is implemented by Jedis. In SpringBoot 2.x, the default client is implemented by Lettuce.

Lettuce compared with Jedis

Both Lettuce and Jedis are clients that connect to Redis Server.

Jedis is implemented as a direct connection to Redis Server, which is not thread-safe in a multi-threaded environment, unless a connection pool is used to add physical connections to each Redis instance.


Lettuce is a scalable, thread-safe, non-blocking Redis client, multiple threads can share a RedisConnection, it uses Netty NIO framework to efficiently manage multiple connections, thus providing asynchronous and synchronous data access. For building non-blocking, reactive applications.


The following uses Lettuce and Jedis respectively to integrate Redis services

Lettuce integrate Redis service

Import dependence

Since Spring Boot 2.X has default integration with Lettuce, there is no need to import.

Application.properties configuration file

################ Redis basic configuration ##############
# Redis database index (default 0)
spring.redis.database=0  
# Redis server addressSpring. Redis. Host = 127.0.0.1# Redis server connection port
spring.redis.port=6379  
# Redis server connection password (default null)
spring.redis.password=zwqh
# link timeout in ms (ms)
spring.redis.timeout=3000
################ Redis thread pool Settings ##############
The maximum number of connections in the pool (using negative values to indicate no limit) defaults to 8
spring.redis.lettuce.pool.max-active=8
The maximum connection pool blocking wait time (negative value indicates no limit) defaults to -1
spring.redis.lettuce.pool.max-wait=-1
The maximum number of free connections in the connection pool defaults to 8
spring.redis.lettuce.pool.max-idle=8
The minimum free connection in the connection pool defaults to 0
spring.redis.lettuce.pool.min-idle=0

Copy the code

Custom RedisTemplate

By default, templates can only support RedisTemplate

, which can only store strings. Many times, we need to customize the RedisTemplate and set up the serializer so that we can easily manipulate instance objects. As follows:
,string>

@Configuration
public class LettuceRedisConfig {

	@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);
		returnredisTemplate; }}Copy the code

Serialized entity class

public class UserEntity implements Serializable {

	/ * * * * /
	private static final long serialVersionUID = 5237730257103305078L;
	
	private Long id;
	private String userName;
	private String userSex;
	public Long getId(a) {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName(a) {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserSex(a) {
		return userSex;
	}
	public void setUserSex(String userSex) {
		this.userSex = userSex; }}Copy the code

Unit testing


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {

	@Autowired
	private RedisTemplate<String, String> strRedisTemplate;
	@Autowired
	private RedisTemplate<String, Serializable> serializableRedisTemplate;
	
	@Test
	public void testString(a) {
		strRedisTemplate.opsForValue().set("strKey"."zwqh");
		System.out.println(strRedisTemplate.opsForValue().get("strKey"));
	}
	
	@Test
	public void testSerializable(a) {
		UserEntity user=new UserEntity();
		user.setId(1L);
		user.setUserName("Morning fog light cold");
		user.setUserSex("Male");		
		serializableRedisTemplate.opsForValue().set("user", user);		
		UserEntity user2 = (UserEntity) serializableRedisTemplate.opsForValue().get("user");
		System.out.println("user:"+user2.getId()+","+user2.getUserName()+","+user2.getUserSex()); }}Copy the code

The result is as follows:

3.Jedis integrates Redis service

Pom file

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.9. RELEASE</version>
		<relativePath /> <! -- lookup parent from repository -->
	</parent>
	<groupId>cn.zwqh</groupId>
	<artifactId>spring-boot-redis</artifactId>
	<version>0.0.1 - the SNAPSHOT</version>
	<name>spring-boot-redis</name>
	<description>spring-boot-redis</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<! -- Redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<exclusions>
				<! Mysql > delete the oracle package.
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<! -- Add jedis client -->
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>
	
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Copy the code

Application.properties configuration file

# # # # # # # # # # # # # # # # Redis based configuration # # # # # # # # # # # # # # # Redis database index (the default is 0) spring. Redis. Database = 0 # Redis server address Port =6379 # Redis server connection password (default empty) spring.redis. Password = ZWQH # Link timeout unit ms (ms) Spring.redis. timeout=3000 ################ Redis thread pool Settings ############### Maximum number of connections in a connection pool (negative values indicate no limit) Default 8 Spring. Redis. Jedis. Pool. Max - active = 8 # connection pool biggest jam waiting time (use a negative value indicates no limit) - 1 spring. By default redis. Jedis. Pool. The Max - wait = 1 # the maximum idle connections in the connection pool Default 8 spring. Redis. Jedis. Pool. Max - idle = 8 # connection pool in minimum free connection 0 spring. By default redis. Jedis. Pool. Min - idle = 0Copy the code

JedisRedisConfig

@Configuration
public class JedisRedisConfig {

	@Value("${spring.redis.database}")
	private int database;
	@Value("${spring.redis.host}")
	private String host;
	@Value("${spring.redis.port}")
	private int port;
	@Value("${spring.redis.password}")
	private String password;
	@Value("${spring.redis.timeout}")
	private int timeout;
	@Value("${spring.redis.jedis.pool.max-active}")
	private int maxActive;
	@Value("${spring.redis.jedis.pool.max-wait}")
	private long maxWaitMillis;
	@Value("${spring.redis.jedis.pool.max-idle}")
	private int maxIdle;
	@Value("${spring.redis.jedis.pool.min-idle}")
	private int minIdle;

	/** * Connection pool configuration information */

	@Bean
	public JedisPoolConfig jedisPoolConfig(a) {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		// Maximum number of connections
		jedisPoolConfig.setMaxTotal(maxActive);
		// Maximum wait time when no connection is available in the pool
		jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
		// Maximum number of idle connections
		jedisPoolConfig.setMinIdle(maxIdle);
		// Minimum number of free connections
		jedisPoolConfig.setMinIdle(minIdle);
		// Other attributes can be added by yourself
		return jedisPoolConfig;
	}

	/** * Jedis connects to **@param jedisPoolConfig
	 * @return* /
	@Bean
	public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
		JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling()
				.poolConfig(jedisPoolConfig).and().readTimeout(Duration.ofMillis(timeout)).build();
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName(host);
		redisStandaloneConfiguration.setPort(port);
		redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
		return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
	}

	/** * Cache manager **@param connectionFactory
	 * @return* /
	@Bean
	public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
		return RedisCacheManager.create(connectionFactory);
	}

	@Bean
	public RedisTemplate<String, Serializable> redisTemplate(JedisConnectionFactory connectionFactory) {
		RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		redisTemplate.setConnectionFactory(jedisConnectionFactory(jedisPoolConfig()));
		returnredisTemplate; }}Copy the code

Same for unit tests

Expected results occur.

conclusion

We have described how Spring Boot 2.X can integrate Redis services through Lettuce and Jedis. Depending on the project requirements, we can also customize action classes to implement data manipulation.

The sample code

github

Yards cloud

The copyright of this article belongs to Chaowu And Qinghan, please indicate the source.

Spring Boot 2.X(vi) : Spring Boot integrates with Redis

The original address: https://www.zwqh.top/article/info/11

If the article is helpful to you, please scan the code to pay attention to my public number, the article continues to update…