springcloud use zull + redis + spring-session realize session sharing, and solve pit session ajax request is not shared

1. First introduced in the respective dependent redis the pom.xml

1  <!--添加redis-->
2         <dependency>
3             <groupId>org.springframework.boot</groupId>
4             <artifactId>spring-boot-starter-data-redis</artifactId>
5         </dependency>
6         <dependency>
7             <groupId>org.springframework.session</groupId>
8             <artifactId>spring-session-data-redis</artifactId>
9         </dependency>

2. Add configuration information in application.properties in redis

 1 #添加redis
 2 spring.redis.database=0
 3 spring.redis.host=localhost
 4 spring.redis.port=6379
 5 spring.redis.password=123456
 6 spring.redis.timeout=20000ms
 7 spring.redis.jedis.pool.max-active=8
 8 spring.redis.jedis.pool.max-wait=-1ms
 9 spring.redis.jedis.pool.max-idle=8
10 spring.redis.jedis.pool.min-idle=0

3. Add annotation startup class inside

@SpringBootApplication
@EnableRedisHttpSession(flushMode = FlushMode.IMMEDIATE)
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

4. The need to define the header information in the gateway filtering rules services, zuul default will filter out all header information, which can lead to loss of cookie, you can not remove the data from the session in the redis.

Add application.properties gateway inside

# Header information to be ignored, not propagated to other services 
sensitive-headers: Access-Control-the Allow-Origin 
ignored-headers: Access-Control-the Allow-Origin, H-APP-Id, Token, APPTOKEN 
# This idea needs you register to the service on top of each gateway must add a this
zuul.routes. service name .sensitiveHeaders = "*"
 

5. session and deposit taking session process, spring help us to automatically take complete, save session

 public the Result ifLogin (the HttpSession the session) {
     // save session, spring automatically help us access to the redis 
    session.setAttribute ( "User" , user1);
     // get the session 
    session.getAttribute ( "User" ); 
}        

Here basically can be achieved in the session session between different services to share, and if not, please read on

  • The first solution there is a direct redis inside, and then pick up directly between the different services
  • @Autowired
     private RedisTemplate redisTemplate;
    @RequestMapping("login")
      public String login(){
        //直接将session存入到redis中
        redisTemplate.opsForValue().set("user",user);
       //然后取
      redisTemplate.opsForValue().get("user");       
    }

     

Note: If you were to send a request using ajax, you find that no matter what, session can not be shared, even between different requests of the same controller, session are not shared, then you need to set the following:

// use native ajax 
$ .ajax ({ 
            url: "HTTP: // localhost: 8080 / the Orders" , 
            of the type: "GET" ,
 // here is the key 
            xhrFields: { 
                withCredentials: to true 
            }, 
            crossdomain: to true , 
            Success: function (Data) { 
                the render (Data); 
            } 
 }); 
If you are using .post $ ( "HTTP: //192.168.10.*/user/user/ifLogin", the callback, "JSON" ) 
need to set ajax global transmission request mode, the request to bring the head, and compare their own native glance 
$ ( function  () {
    $ .ajaxSetup ({xhrFields: {
            withCredentials: true
        }})
})
  • Also you need to set some configuration in which the gateway zuul
@Configuration
 public  class CorsConfig { 
    @Bean 
    public CorsFilter corsFilter () {
         Final UrlBasedCorsConfigurationSource Source = new new UrlBasedCorsConfigurationSource ();
         Final CorsConfiguration config = new new CorsConfiguration (); 
        config.setAllowCredentials ( to true ); // allow cross-domain cookies 
        config.addAllowedOrigin ( " * "); // # commit request to allow server URI, * represents all allowed, in SpringMVC if * is set to automatically switch to the current request header Origin 
        config.addAllowedHeader (" * "); / / # allow access to header information, * means all 
        config.setMaxAge (7200L); //Preflight request cache time (in seconds), i.e., in this time period, the same cross-domain request will not be the preflight 
        config.addAllowedMethod ( "*"); // method allowing to submit the request, * represents all allowed 
        source.registerCorsConfiguration ( "/ **" , config);
         return  new new CorsFilter (Source); 
    } 
}
package com.study.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class FirstFilter extends ZuulFilter {
    /**
     * Pre: can be called before the request is routed 
     * route: a route request is invoked when 
     * post: after the route is called filter and error 
     * error: is called when an error occurred while processing a request 
     * 
     * @return 
     * / 
    @Override 
    public String filterType () {
         return FilterConstants.PRE_TYPE; 
    } 

    / ** 
     * priority of 0, the larger the number, the lower the priority 
     * 
     * @return 
     * / 
    @Override 
    public  int filterOrder () {
         return FilterConstants.PRE_DECORATION_FILTER_ORDER -. 1 ; 
    } 

    @Override 
    public  Boolean shouldFilter () {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        HttpServletRequest request = ctx.getRequest();
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        response.setHeader ( "Access-Control-the Allow-Headers", "X-Access-token, Content-type" ); 
        response.setHeader ( "Access-Control-Expose-Headers", "X--forwared-Port, X- Host-Forwarded " ); 
        response.setHeader ( " Vary "," Origin,-Access-Control-Method, the request, the request-Access-Control-Headers " );
         // cross-domain request will be a total of two options if a request to send may request 
        IF ( "the OPTIONS" .equalsIgnoreCase (request.getMethod ())) { 
            ctx.setSendZuulResponse ( to false ); // verification request is not routed 
            ctx.setResponseStatusCode (HttpStatus.OK.value ());// returns successful status code verification 
            return  null ;
        } 
        Ctx.setSendZuulResponse ( to true ); // routes requests 
        ctx.setResponseStatusCode (HttpStatus.OK.value ());
         return  null ; 
    } 
}

 

Well, basically like this, this, I also tangled a day, conclude, the desire to help you later

Guess you like

Origin www.cnblogs.com/nukill/p/11853591.html