1. Redis
As a non relational database, Redis is widely used in project development, especially as a data cache to ensure the rapid response of requested data and improve the user experience of the service.
Today, let's learn how to integrate Redis as a cache database in the Spring Boot project.
1.1 introducing Redis related dependencies
Spring boot encapsulates the set of Redis and provides Spring Data Redis framework support. Spring Data Redis defines the logic of interacting with Redis database in the underlying spring architecture. Users do not need to care about how to manage it when using it, but only need to operate Redis at the application level.
The starter data redis dependency needs to be cited when using:
<!-- redis Dependent information --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> Copy code
1.2 dependency information
After dependency is introduced, you can see the related dependency package information in maven projects, including spring data redis and lettuce core.
- Spring data redis contains some public packages for data processing in spring
- The lettuce core package is the default support for lettuce in starter data redis
1.3 Jedis client dependency
If you need to use Jedis to operate Redis, you only need to replace the lettuce dependency with Jedis.
<!--Import jedis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> Copy code
2. Redis configuration
Spring Boot provides automatic configuration for redis in the org.springframework.boot.autoconfigure.data.redis package. It is defined as:
- RedisAutoConfiguration autoconfiguration class
- RedisPropertiesRedis property information reading class
- RedisConnectionConfiguration connection configuration base class
- JedisConnectionConfiguration, Jedis connection configuration class
- Letticeconnectionconfiguration, letticeconnectionconfiguration class
2.1 Redis information is defined in the configuration file
Once RedisProperties are available and redis related properties are defined in the Spring Boot configuration file, they will be injected into redis when the project is started. Redis can customize the following configuration items:
# Redis configuration item, prefixed with spring.redis # Database index (0 by default) spring.redis.database=0 # server address spring.redis.host=127.0.0.1 # port spring.redis.port=6379 # Password (blank by default, this property is not set when it is blank) spring.redis.password=redis # Timeout (MS) spring.redis.timeout=30000 # It is recommended to use lettuce instead of jedis. spring integrates lettuce by default spring.redis.client-type=lettuce # If the jedis client is used, the content defined below needs to replace lettuce with jedis # Maximum number of connections in the connection pool (negative value indicates no limit) spring.redis.lettuce.pool.max-active=10 # Maximum blocking wait time (use a negative value to indicate no limit) spring.redis.lettuce.pool.max-wait=-2 # Maximum number of free connections spring.redis.lettuce.pool.max-idle=10 # Minimum idle connection spring.redis.lettuce.pool.min-idle=0 Copy code
2.2 customize Redis configuration class
As mentioned earlier, spring defines a special RedisAutoConfiguration automatic configuration class for redis, which defines the creation of RedisTemplate objects with generic type < object, Object >. In order to allow custom configuration of beans, the automatic configuration class uses @ ConditionalOnMissingBean annotation to indicate that when a RedisTemplate Bean is defined elsewhere, it will replace the results in automatic configuration.
@Configuration( proxyBeanMethods = false ) @ConditionalOnClass({RedisOperations.class}) @EnableConfigurationProperties({RedisProperties.class}) @Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class}) public class RedisAutoConfiguration { public RedisAutoConfiguration() { } @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 new StringRedisTemplate(redisConnectionFactory); } } Copy code
To facilitate operation, we define a < string, Object > generic RedtTemplate, which is more suitable for data storage and reading.
- RedisTemplate serialization adopts JDK serialization policy by default, which can be set as other policies 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); //The serialization method of String is adopted redisTemplate.setKeySerializer(new StringRedisSerializer()); // value is serialized by jackson redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } Copy code
3. Use Redis
3.1 Redis is used in the springboot project
After configuring Redis in the project, you can directly execute the project. During operation, you need to pay attention to whether the Redis information defined in the configuration file is correct. If Redis cannot connect, an error will be reported when the project is started.
- The server address is the service address where Redis runs. If it is local, it is 127.0.0.1
- Set the port number of Redis startup. The default is 6379
- Redis connection password is the password to start redis service in the server. If there is no password, do not configure this attribute, otherwise an error will be reported
After the project is successfully started, in order to verify whether redis is available, redisTemplate can be used in unit test to store and obtain data into redis.
@Autowired private RedisTemplate redisTemplate; @Test public void testRedis(){ ValueOperations<String, String> operations = redisTemplate.opsForValue(); operations.set("name", "tom"); System.out.println(operations.get("name")); } Copy code
After executing the unit test, the stored tom value is output, indicating that the data has been stored in Redis.
3.2 installing Redis under Windows
If the Redis service is not installed, or you want to view the stored data in the Redis service, you can refer to the creation method of windows local Redis service.
Redis official does not recommend using redis under windows, so the Windows version is not provided, while Microsoft official provides available redis applications for Windows users.
Redis version under windows , you can select the installation package or installation free version when downloading.
After downloading and installing, you can get the redis directory. You can use the redis server and redis cli programs to run redis
- As the server, redis server starts the command line to run the redis service
- As a client, redis cli can execute redis related commands to view and store data
If it is an installation free version, the redis service runs in the foreground every time, which is not concise enough. You can also set the redis server to start in the background through the windows command line. Relevant commands are:
- Decompress the redis program and put it in the appropriate location
- Open a command window, enter the decompression directory, and enter the command: redis server redis.windows.conf
- Open a new command window and enter the command: redis server -- service install redis.windows.conf
- In this way, redis can be deployed as a service under windows
- After installation, use the command to start the service: redis server -- service start
- If you want to stop or uninstall the redis service, you only need to execute the relevant commands
- Stop service command: redis server -- service stop
- Redis uninstall command: redis server -- service uninstall
After entering the redis client, you can use the redis command to view the stored data: