Turn: https://www.cnblogs.com/mengmeng89012/p/5519698.html
This time I bring the tutorial of spring boot + redis to achieve session sharing.
In the spring boot documentation, tell us to add @EnableRedisHttpSession to enable spring session support, the configuration is as follows:
- @Configuration
- @EnableRedisHttpSession
- public class RedisSessionConfig {
- }
The @EnableRedisHttpSession annotation is provided by spring-session-data-redis, so add in the pom.xml file:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-redis</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.session</groupId>
- <artifactId>spring-session-data-redis</artifactId>
- </dependency>
Next, you need to configure the location of the redis server in application.properties. Here, we use the machine:
- spring.redis.host=localhost
- spring.redis.port=6379
In this way, the simplest spring boot + redis to achieve session sharing is completed, the following test.
First, we opened two tomcat services, ports, respectively, 8080 and 9090, is set in the application.properties [Download] :
- server.port=8080
Next, define a Controller:
- @RestController
- @RequestMapping(value = "/admin/v1")
- public class QuickRun {
- @RequestMapping(value = "/first", method = RequestMethod.GET)
- public Map<String, Object> firstResp (HttpServletRequest request){
- Map<String, Object> map = new HashMap<>();
- request.getSession().setAttribute("request Url", request.getRequestURL());
- map.put("request Url", request.getRequestURL());
- return map;
- }
- @RequestMapping(value = "/sessions", method = RequestMethod.GET)
- public Object sessions (HttpServletRequest request){
- Map<String, Object> map = new HashMap<>();
- map.put("sessionId", request.getSession().getId());
- map.put("message", request.getSession().getAttribute("map"));
- return map;
- }
- }
After the start of the access test, first visit the tomcat port 8080, return to get [download address] :
- {"request Url":"http://localhost:8080/admin/v1/first"}
Next, we access the sessions on port 8080 and return:
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
Finally, visit sessions on port 9090 and return:
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
It can be seen that the results returned by the two servers 8080 and 9090 are the same, sharing the session
If you access the first port 9090 at this time, first return:
- {"request Url":"http://localhost:9090/admin/v1/first"}
The sessions of both servers are returned:
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"}
It is very simple to realize session sharing through spring boot + redis, and it is also very useful. With nginx for load balancing, distributed applications can be realized.
-------------------------------------------------------
Add cache
RedisCacheConfig
package com.lzw.core.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by ZhenWeiLai on 2017/6/11. */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class); @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.pool.max-wait}") private long maxWaitMillis; @Value("${spring.redis.password}") private String password; @Bean public JedisPool redisPoolFactory() { logger.info("JedisPool注入成功!!"); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); return jedisPool; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory (cf); return redisTemplate; } @Bean public CacheManager cacheManager (RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager (redisTemplate); // default timeout, unit seconds cacheManager.setDefaultExpiration (3000 ); // Set the timeout according to the cache name, 0 means no timeout Map <String, Long> expires = new ConcurrentHashMap <> (); cacheManager.setExpires (expires); return cacheManager; } }
application.yml
spring: datasource: # readSize: 1 # name: writeDataSource type: com.alibaba.druid.pool.DruidDataSource write: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&useSSL=true username: root password: 123 initialSize: 10 maxActive: 100 maxWait: 60000 minIdle: 5 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 'x' max-idle: 8 testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 #redis configuration redis: host: 192.168.1.11 port: 6379 # REDIS (RedisProperties) # Redis database index (default is 0) database: 0 # Redis server connection password (Default is empty) password: # maximum number of connections in the connection pool (use a negative value to indicate no limit) # connection timeout time (milliseconds) timeout: 0 pool: max-active: 8 # connection pool maximum blocking wait time (use a negative value to indicate No limit) max-wait: -1 # The largest idle connection in the # The minimum idle connection in the connection pool min-idle: 0