springBoot--integrated springsession to use redis to achieve session sharing

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:

Java code   Favorite Code
  1. @Configuration  
  2. @EnableRedisHttpSession  
  3. public class RedisSessionConfig {  
  4. }  

The @EnableRedisHttpSession annotation is provided by spring-session-data-redis, so add in the pom.xml file:

Java code   Favorite Code
  1. <dependency>  
  2.         <groupId>org.springframework.boot</groupId>  
  3.         <artifactId>spring-boot-starter-redis</artifactId>  
  4. </dependency>  
  5. <dependency>  
  6.         <groupId>org.springframework.session</groupId>  
  7.         <artifactId>spring-session-data-redis</artifactId>  
  8. </dependency>  

 

 

Next, you need to configure the location of the redis server in application.properties. Here, we use the machine:

Java code   Favorite Code
  1. spring.redis.host=localhost  
  2. 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]    :

Java code   Favorite Code
  1. server.port=8080  

 

Next, define a Controller: 

Java code   Favorite Code
  1. @RestController  
  2. @RequestMapping(value = "/admin/v1")  
  3. public class QuickRun {  
  4.     @RequestMapping(value = "/first", method = RequestMethod.GET)  
  5.     public Map<String, Object> firstResp (HttpServletRequest request){  
  6.         Map<String, Object> map = new HashMap<>();  
  7.         request.getSession().setAttribute("request Url", request.getRequestURL());  
  8.         map.put("request Url", request.getRequestURL());  
  9.         return map;  
  10.     }  
  11.   
  12.     @RequestMapping(value = "/sessions", method = RequestMethod.GET)  
  13.     public Object sessions (HttpServletRequest request){  
  14.         Map<String, Object> map = new HashMap<>();  
  15.         map.put("sessionId", request.getSession().getId());  
  16.         map.put("message", request.getSession().getAttribute("map"));  
  17.         return map;  
  18.     }  
  19. }  

 

After the start of the access test, first visit the tomcat port 8080, return to  get [download address]    :

Java code   Favorite Code
  1. {"request Url":"http://localhost:8080/admin/v1/first"}  

 Next, we access the sessions on port 8080 and return:

Java code   Favorite Code
  1. {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}  

Finally, visit sessions on port 9090 and return:

Java code   Favorite Code
  1. {"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:

Java code   Favorite Code
  1. {"request Url":"http://localhost:9090/admin/v1/first"}  

The sessions of both servers are returned:

Java code   Favorite Code
  1. {"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
Copy code
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; 
    } 
}
Copy code

 application.yml

Copy code
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

Published 7 original articles · 69 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/u014320421/article/details/79620811
Recommended