微服务: feign 的请求拦截器 执行token拦截, 接口无需传递token

 

目录

 1. 源码: 

2. 修改拦截器的返回值方式


前言: 略, 逻辑略, 直接用, 就不过多解释, 之后整个feign总结时添加


 1. 源码: 


package feign;

public interface RequestInterceptor {
    void apply(RequestTemplate var1);
}

2. 修改拦截器的返回值方式

package aisce.config;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author pzy
 * @since 2022-11-21
 * @version 0.0.1
 */
@Configuration
public class FeignConfiguration {

    private static String token = "";

    @Bean
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            //获取请求信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            //获取在session中的token信息
            token = request.getHeader("token");
            System.out.println("RequestTemplateToken-->" + FeignConfiguration.token);

            List accessToken = Lists.newArrayList( FeignConfiguration.token);

            List contentTypeList = Lists.newArrayList("application/json");

            Map> headers = ImmutableMap.of("token", accessToken,"Content-Type", contentTypeList);

            requestTemplate.headers(headers);
        };
    }
}

你可能感兴趣的:(#,SpringCloud微服务,微服务,java,架构)