SpringBoot+SpringCloud實現登陸用戶信息在微服務之間的傳遞

實現思路:java

1:準備一個ThreadLocal變量,供線程之間共享。spring

2:每一個微服務對全部過來的Feign調用進行過濾,而後從請求頭中獲取User用戶信息,並存在ThreadLocal變量中。apache

3:每一個微服務在使用FeignClient調用別的微服務時,先從ThreadLocal裏面取出user信息,並放在request的請求頭中。json

4:封裝爲一個註解,在啓動類上標記便可。mybatis

代碼樣例:app

1:ThreadLocal工具類 :UserInfoContext dom

package com.test.domi.common.system;

import com.test.domi.dao.UserInfo;

public class UserInfoContext {
    private static ThreadLocal<UserInfo> userInfo = new ThreadLocal<UserInfo>();
    public static String KEY_USERINFO_IN_HTTP_HEADER = "X-AUTO-FP-USERINFO";

    public UserInfoContext() {
    }

    public static UserInfo getUser(){
        return (UserInfo)userInfo.get();
    }

    public static void setUser(UserInfo user){
        userInfo.set(user);
    }
}

2:準備承載用戶信息的userInfo實體類(代碼略)ide

3:編寫攔截器 : TransmitUserInfoFeighClientIntercepter 微服務

package com.test.domi.config;

import com.alibaba.fastjson.JSON;
import com.test.domi.common.system.UserInfoContext;
import com.test.domi.dao.UserInfo;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class TransmitUserInfoFeighClientIntercepter implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(TransmitUserInfoFeighClientIntercepter.class);
    public TransmitUserInfoFeighClientIntercepter() {
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //從應用上下文中取出user信息,放入Feign的請求頭中
        UserInfo user = UserInfoContext.getUser();
        if (user != null) {
            try {
                String userJson = JSON.toJSONString(user);
                requestTemplate.header("KEY_USERINFO_IN_HTTP_HEADER",new String[]{URLDecoder.decode(userJson,"UTF-8")});
            } catch (UnsupportedEncodingException e) {
                log.error("用戶信息設置錯誤",e);
            }
        }
    }
}

 

4:編寫過濾器:TransmitUserInfoFilter 工具

package com.test.domi.config;

import com.alibaba.fastjson.JSON;
import com.test.domi.common.system.UserInfoContext;
import com.test.domi.dao.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class TransmitUserInfoFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(TransmitUserInfoFeighClientIntercepter.class);
    public TransmitUserInfoFilter() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       this.initUserInfo((HttpServletRequest)request);
       chain.doFilter(request,response);
    }

    private void initUserInfo(HttpServletRequest request){
        String userJson = request.getHeader("KEY_USERINFO_IN_HTTP_HEADER");
        if (StringUtils.isNotBlank(userJson)) {
            try {
                userJson = URLDecoder.decode(userJson,"UTF-8");
                UserInfo userInfo = (UserInfo) JSON.parseObject(userJson,UserInfo.class);
                //將UserInfo放入上下文中
                UserInfoContext.setUser(userInfo);
            } catch (UnsupportedEncodingException e) {
               log.error("init userInfo error",e);
            }
        }
    }

    @Override
    public void destroy() {
    }
}

 

5:編寫註解實現類: EnableUserInfoTransmitterAutoConfiguration 

 
 
package spring.cloud.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import spring.cloud.common.interceptor.TransmitUserInfoFeighClientInterceptor;
import spring.cloud.common.filter.TransmitUserInfoFilter;

//@Configuration 在業務端經過註解EanbleUserInfoTransmitter加載
public class EnableUserInfoTransmitterAutoConfiguration {

public EnableUserInfoTransmitterAutoConfiguration() {
}

@Bean
public TransmitUserInfoFeighClientInterceptor transmitUserInfo2FeighHttpHeader(){
System.out.println("-----TransmitUserInfoFeighClientInterceptor");
return new TransmitUserInfoFeighClientInterceptor();
}

@Bean
public TransmitUserInfoFilter transmitUserInfoFromHttpHeader(){
System.out.println("-----TransmitUserInfoFilter");
return new TransmitUserInfoFilter();
}
}
 

6:編寫註解 EnableUserInfoTransmitter 

package com.test.domi.annotation;

import com.test.domi.config.EnableUserInfoTransmitterAutoConfiguration;
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import({EnableUserInfoTransmitterAutoConfiguration.class})
public @interface EnableUserInfoTransmitter {
}

7:在啓動類上標記註解便可使用(無侵入)

package com.test.domi;

import com.test.domi.annotation.EnableUserInfoTransmitter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
@MapperScan("com.test.domi.dao")
@EnableUserInfoTransmitter public class TestCommonClient {

    public static void main(String[] args){

        SpringApplication.run(TestCommonClient.class,args);
    }
}
相關文章
相關標籤/搜索