Springboot + Redis +springsession Cache Introduction
A few days ago, brother studied learned thatEhCacheit is an in-process caching framework, and although it has provided a cache synchronization strategy in a clustered environment, this synchronization will still take some time, that is to some extent, the short-term cache inconsistency still exists.
So, I chose the centralized cache and used Redis in the Springboot project for caching.
Personal Reference case
Personal blog: https://zggdczfr.cn/
Personal Reference case (if approved, Trouble to star): Https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B10
A Spring Boot + Redis1. Installing Redis
Redis was originally not supported in Windows operating system installation run, but later with window support, put the link (specific installation Baidu a bit): https://github.com/MSOpenTech/redis/releases
Note: It is recommended to use 2.8+ above Reids version, otherwise it will conflict with Springseeeion!
2. Add dependencies
Create a new Springboot project and configure the Mybatis+druid. Add Redis cache support in the Pom.xml file.
<!-Cache dependency->
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-cache </ artifactId>
</ dependency>
<!-spring boot redis dependency->
<dependency>
<groupId> org.springframework.boot </ groupId>
<artifactId> spring-boot-starter-redis </ artifactId>
</ dependency>
3. Application.properties Configuration
For Redis configuration parameters:
# Redis configuration (default configuration)
# Redis database index (default is 0)
spring.redis.database = 0
# Redis server address
spring.redis.host = localhost
# Redis server port
spring.redis.port = 6379
# Redis server password (default is empty)
spring.redis.password =
# Maximum number of connections in the connection pool (use a negative value to indicate no limit)
spring.redis.pool.max-active = 8
# Maximum idle connection in the connection pool
spring.redis.pool.max-idle = 8
# The smallest idle connection in the connection pool
spring.redis.pool.min-idle = 0
# Connection pool maximum blocking wait time (use a negative value to indicate no limit)
spring.redis.pool.max-wait = -1
# Set connection timeout
spring.redis.timeout = 0
4. About Springboot Cache annotations
In an environment that supports Spring Cache,
- @EnableCaching: Turn on the springboot cache policy and put it on the startup main class.
- @CacheConfig(cacheNames = "XXX"): Set a cache space named "XXX".
- @Cacheable: Spring checks to see if there is a cache element of the same key in the cache before each execution, and if it does not execute the method, it returns the result directly from the cache, otherwise it is executed and the returned result is stored in the specified cache.
- @CacheEvict: Clears the cache.
- @CachePut:@CachePutYou can also declare a method that supports caching functionality. The@CachePutmethod used for labeling does not check for the existence of previously executed results in the cache until it executes, but executes the method every time and stores the execution result as a key-value pair in the specified cache.
5. Adding a Redis configuration class
Important Reference information: Http://www.jianshu.com/p/a2ab17707eff
This class is primarily about adding a serialization tool to Redis, which Springboot doesn't encapsulate (or I can't find).
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value ("$ {spring.redis.host}")
private String host;
@Value ("$ {spring.redis.port}")
private int port;
@Value ("$ {spring.redis.timeout}")
private int timeout;
@Bean
public KeyGenerator wiselyKeyGenerator () {
return new KeyGenerator () {
@Override
public Object generate (Object o, Method method, Object ... objects) {
StringBuilder sb = new StringBuilder ();
sb.append (o.getClass (). getName ());
sb.append (method.getName ());
for (Object obj: objects) {
sb.append (obj.toString ());
}
return sb.toString ();
}
};
}
@Bean
public JedisConnectionFactory redisConnectionFactory () {
JedisConnectionFactory factory = new JedisConnectionFactory ();
factory.setHostName (host);
factory.setPort (port);
factory.setTimeout (timeout); // Set connection timeout
return factory;
}
@Bean
public CacheManager cacheManager (RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager (redisTemplate);
cacheManager.setDefaultExpiration (10); // Set key-value timeout
return cacheManager;
}
@Bean
public RedisTemplate <String, String> redisTemplate (RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate (factory);
setSerializer (template); // Set the serialization tool without having to implement the Serializable interface
template.afterPropertiesSet ();
return template;
}
private void setSerializer (StringRedisTemplate template) {
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);
template.setValueSerializer (jackson2JsonRedisSerializer);
}
}
Other
Other code is not cumbersome to post, direct reference to my GitHub warehouse: https://github.com/FunriLy/springboot-study/tree/master/%E6%A1%88%E4%BE%8B10
After starting the project, visit Http://localhost:8080/redis and we can see the following results in the console:
No caching! 8b10aba26bd5402bbdad2584d8452f1f
User {uuid = ‘8b10aba26bd5402bbdad2584d8452f1f’, name = ‘张三’, age = 20}
User {uuid = ‘8b10aba26bd5402bbdad2584d8452f1f’, name = ‘张三’, age = 20}
====== Modify Redis cache data ======
User {uuid = ‘8b10aba26bd5402bbdad2584d8452f1f’, name = ‘李四’, age = 18}
User {uuid = ‘8b10aba26bd5402bbdad2584d8452f1f’, name = ‘李四’, age = 18}
Add: If you still do not know, you can check my previous blog Spring Boot Learning (13) Springboot cache (EhCache 2.x), which uses the log4j debug mode in detail to print the executed SQL statements, Or use the Druid console to view the execution of the SQL statement.
Two Spring Session
In distributed systems, there are many solutions to sessiong sharing, where hosting into the cache should be one of the most common scenarios.
Springsession principle
@EnableRedisHttpSessionThis annotation creates a bean named Springsessionrepositoryfilter, which is responsible for replacing the httpSession while providing cache support from Redis.
maxInactiveIntervalInSeconds: Sets the session expiration time. The Server.session.timeout property of the original boot is no longer valid after using the Redis session.
1. Add Springsession Configuration Class
@Configuration
@EnableRedisHttpSession (maxInactiveIntervalInSeconds = 86400 * 30)
public class HttpSessionConfig {
// no configuration by default
}
2. Add a validated URL interface
@Value ("$ {server.port}")
String port;
@RequestMapping (value = "/ session", method = RequestMethod.GET)
public Object getSession (HttpServletRequest request) {
Map <String, Object> map = new HashMap <String, Object> ();
map.put ("SessionId", request.getSession (). getId ());
map.put ("ServerPort", "The service port number is" + port);
return map;
}
Simultaneous launch of two identical projects (e.g. 8080 ports and 9090 ports), access to Http://localhost:8080/session and http://localhost:9090/session
We can get the following results:
{"SessionId": "01f353e1-5cd3-4fbd-a5d0-9a73e17dcec2", "ServerPort": "The service port number is 8080"}
{"SessionId": "01f353e1-5cd3-4fbd-a5d0-9a73e17dcec2", "ServerPort": "The service port number is 9090"}
The results of the SessionID are consistent, but are provided by two different project projects to provide services. In this way, Springsession uses the Interceptor filter to help us synchronize the settings before each request, to achieve session sharing in the distributed system.
Spring Boot Learning (14) Springboot+redis+springsession Cache