“This is the 25th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

1. Redis

As a non-relational database, Redis is widely used in project development, especially as a cache of data to ensure a fast response to request data and improve the user experience of the service.

Today we will learn how to integrate Redis as a cache database in the Spring Boot project.

1.1 Introduction of Redis-related dependencies

SpringBoot encapsulates the Redis set and provides Spring Data Redis framework support. Spring Data Redis defines the logic of interaction with Redis database in the underlying Spring architecture. Users do not need to care about how to manage when using it. You only need to manipulate Redis at the application level.

Starter-data-redis dependency is used:

<! -- Redis relies on information -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code

1.2 Dependencies Include information

After the dependency is introduced, you can see the relevant dependency package information in Maven Projects, including the spring-data-redis and author-core dependencies.

  • spring-data-redisContains some common packages for Spring’s handling of data
  • lettuce-coreThe package is the default support for lettuce in starter-data-redis

1.3 Jedis client dependencies

If you need to use Jedis to manipulate Redis, just replace the lettuce dependency with Jedis.

<! - import jedis -- -- >        
<dependency>            
    <groupId>redis.clients</groupId>            
    <artifactId>jedis</artifactId>        
</dependency>
Copy the code

2. The Redis configuration

Spring the Boot in org. Springframework. Boot. Autoconfigure. Data. Redis package provides the redis configuration automatically. The definitions are:

  • RedisAutoConfigurationAuto-configuration class
  • RedisPropertiesRedis property information read class
  • RedisConnectionConfigurationConnection configuration base class
    • JedisConnectionConfigurationJedis connection configuration class
    • LettuceConnectionConfiguration, the connection configuration class

2.1 Redis information is defined in the configuration file

With RedisProperties and redIS-related properties defined in the Spring Boot configuration file, they will be injected into Redis at project startup. Redis allows you to customize the following configuration items:

# Redis configuration item prefixed with spring.redis
# database index (default 0)
spring.redis.database=0
# server address
spring.redis.host=127.0.0.1
# port
spring.redis.port=6379
# password (null by default, null if this property is not set)
spring.redis.password=redis
# timeout (ms)
spring.redis.timeout=30000

# suggest using lettuce can be replaced by jedis, spring integrates lettuce by default
spring.redis.client-type=lettuce

If you use the jedis client, the following definition needs to replace the lettuce with jedis
# maximum number of connections in the pool (use negative values to indicate no limit)
spring.redis.lettuce.pool.max-active=10
# Maximum blocking wait time (use negative values to indicate no limit)
spring.redis.lettuce.pool.max-wait=2 -
# Maximum number of idle connections
spring.redis.lettuce.pool.max-idle=10
Minimum idle connection
spring.redis.lettuce.pool.min-idle=0
Copy the code

2.2 Custom Redis configuration classes

Spring defines a RedisAutoConfiguration class for Redis, which creates a RedisTemplate Object with the generic type
. In order to allow custom configuration beans, The auto-configuration class uses the @conditionalonmissingBean annotation to indicate that the result in auto-configuration will be replaced when a RedisTemplate Bean is defined elsewhere.,>

@Configuration( proxyBeanMethods = false )
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration(a) {}@Bean
    @ConditionalOnMissingBean( name = {"redisTemplate"} )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
​
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return newStringRedisTemplate(redisConnectionFactory); }}Copy the code

To make it easier to use, we define a

generic RedtTemplate, which is more suitable for storing and reading data.
,>

  • RedisTemplate serialization defaults to the SERIalization strategy of the JDK and can be set to other strategies in the configuration class
// Customize RedisConfig
@Configuration
public class RedisConfig {
​
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // Use String serialization
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // Value serialization uses Jackson
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        returnredisTemplate; }}Copy the code

3. Use Redis

3.1 The SpringBoot project uses Redis

After configuring Redis in the project, you can directly execute the project. During the operation, you need to pay attention to whether the Redis information defined in the configuration file is correct. If the Redis cannot be connected, an error will be reported during the project startup.

  • The server address must be the address of the service Redis is running on, or if it is local127.0.0.1
  • Set the port number for Redis startup. The default is 6379
  • The Redis connection password is the password used to start the Redis service on the server. If there is no password, do not configure this attribute; otherwise, an error will be reported

After a successful project launch, to verify that Redis is available, you can use the redisTemplate in unit tests to store and retrieve data into Redis.

@Autowired
private RedisTemplate redisTemplate;
​
@Test
public void testRedis(a){
    ValueOperations<String, String> operations = redisTemplate.opsForValue();
    operations.set("name"."tom");
    System.out.println(operations.get("name"));
}
Copy the code

Output the stored Tom value after executing the unit test, indicating that the data is already stored in Redis.

3.2 Installing Redis in Windows

If the Redis service is not installed, or you want to view the stored data in the Redis service, you can follow the instructions for creating the Windows Local Redis service.

Redis does not officially recommend using Redis on Windows, so there is no Windows version available, while Microsoft does officially offer Redis apps for Windows users.

Windows Redis version, you can choose to download the installation package or free version.

After the download and installation, you can get the Redis directory. You can use the Redis -server and Redis – CLI programs to run Redis

  • Redis-server functions as a server. After being started, the command line is enabled to run the Redis service
  • Redis – CLI As a client, you can run redis commands to view and store data

If the installation is free, it is not simple to run the Redis service in the foreground every time. You can also set the redis server to start in the background through the Windows command line. The commands are as follows:

  1. Unzip the Redis program and put it in the appropriate location
  2. Open a command window, go to the decompression directory, and enter the command:redis-server redis.windows.conf
  3. Open a new command window and type the command:redis-server --service-install redis.windows.conf
    • This allows you to deploy Redis as a service under Windows
  4. When the installation is complete, start the service with the following command:redis-server --service-start
  5. If you want to stop or uninstall the Redis service, you only need to run the relevant command
    • Stop service command:redis-server --service-stop
    • Redis uninstall command:redis-server --service-uninstall

After logging in to the Redis client, you can run the redis command to view the stored data: