Springboot+springcloud to implement the transfer of login user information between microservices

Source: Internet
Author: User

Implementation ideas:

1: Prepare a threadlocal variable for sharing between threads.

2: Each micro-service filters all the feign calls that come in, and then gets the user information from the request header and exists in the threadlocal variable.

3: Each micro-service in the use of feignclient invoke other microservices, first remove the user information from the threadlocal, and placed in the request header.

4: Encapsulate as an annotation and mark it on the startup class.

Code Sample:

1:threadlocal Tool Class: Userinfocontext

 PackageCom.test.domi.common.system;ImportCom.test.domi.dao.UserInfo; Public classUserinfocontext {Private StaticThreadlocal<userinfo> UserInfo =NewThreadlocal<userinfo>();  Public StaticString Key_userinfo_in_http_header = "X-auto-fp-userinfo";  PublicUserinfocontext () {} Public StaticUserInfo GetUser () {return(UserInfo) userinfo.get (); }     Public Static voidsetUser (UserInfo user) {userinfo.set (user); }}

2: Prepare the UserInfo entity class that hosts user information (code slightly)

3: Writing interceptors: Transmituserinfofeighclientintercepter

 PackageCom.test.domi.config;ImportCom.alibaba.fastjson.JSON;ImportCom.test.domi.common.system.UserInfoContext;ImportCom.test.domi.dao.UserInfo;Importfeign. Requestinterceptor;Importfeign. Requesttemplate;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importjava.io.UnsupportedEncodingException;ImportJava.net.URLDecoder; Public classTransmituserinfofeighclientintercepterImplementsRequestinterceptor {Private Static FinalLogger log = Loggerfactory.getlogger (transmituserinfofeighclientintercepter.class);  PublicTransmituserinfofeighclientintercepter () {} @Override Public voidapply (Requesttemplate requesttemplate) {//Remove the user information from the application context and put it in the feign request headerUserInfo user =Userinfocontext.getuser (); if(User! =NULL) {            Try{String Userjson=json.tojsonstring (user); Requesttemplate.header ("Key_userinfo_in_http_header",NewString[]{urldecoder.decode (Userjson, "UTF-8")}); } Catch(unsupportedencodingexception e) {log.error ("User Information set Error", E); }        }    }}

4: Write Filter: Transmituserinfofilter

 PackageCom.test.domi.config;ImportCom.alibaba.fastjson.JSON;ImportCom.test.domi.common.system.UserInfoContext;ImportCom.test.domi.dao.UserInfo;Importorg.apache.commons.lang.StringUtils;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importjavax.servlet.*;Importjavax.servlet.http.HttpServletRequest;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportJava.net.URLDecoder; Public classTransmituserinfofilterImplementsFilter {Private Static FinalLogger log = Loggerfactory.getlogger (transmituserinfofeighclientintercepter.class);  PublicTransmituserinfofilter () {} @Override Public voidInit (Filterconfig filterconfig)throwsservletexception {} @Override Public voidDoFilter (ServletRequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception { This. Inituserinfo ((httpservletrequest) request);    Chain.dofilter (Request,response); }    Private voidInituserinfo (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); //put UserInfo into contextUserinfocontext.setuser (UserInfo); } Catch(unsupportedencodingexception e) {log.error ("Init userInfo Error", E); } }} @Override Public voiddestroy () {}}

5: Write the annotation implementation class: Enableuserinfotransmitterautoconfiguration

 PackageCom.test.domi.config;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration; @Configuration Public classenableuserinfotransmitterautoconfiguration { Publicenableuserinfotransmitterautoconfiguration () {} @Bean PublicTransmituserinfofeighclientintercepter Transmituserinfo2feighhttpheader () {return NewTransmituserinfofeighclientintercepter (); } @Bean PublicTransmituserinfofilter Transmituserinfofromhttpheader () {return NewTransmituserinfofilter (); }}

6: Writing Annotations 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: Mark Annotations on the Startup class (no intrusion)

 PackageCom.test.domi;ImportCom.test.domi.annotation.EnableUserInfoTransmitter;ImportOrg.mybatis.spring.annotation.MapperScan;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.client.discovery.enablediscoveryclient;@ Enablediscoveryclient@springbootapplication@mapperscan ("Com.test.domi.dao")@EnableUserInfoTransmitter  Public classtestcommonclient { Public Static voidMain (string[] args) {Springapplication.run (testcommonclient.class, args); }}

Springboot+springcloud to implement the transfer of login user information between microservices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.