SpringCloud OpenFeign 服务调用传递 token
在Spring Cloud OpenFeign中传递Token,你可以通过定义一个Feign的拦截器来实现。以下是一个简单的例子:
- 创建一个Feign的拦截器:
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class FeignTokenInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Authorization"); // 假设token在请求头中
template.header("Authorization", token); // 将token添加到请求头中
}
}
}
- 在Feign Client接口中添加该拦截器:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "your-service-name", url = "http://your-service-url", configuration = FeignClientConfiguration.class)
public interface YourServiceClient {
@GetMapping("/endpoint")
String yourMethod();
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfiguration {
@Bean
public RequestInterceptor requestInterceptor() {
return new FeignTokenInterceptor();
}
}
在这个例子中,FeignTokenInterceptor
拦截器会从原始请求中提取出Authorization
token,并将其添加到Feign客户端发起的每个请求中。这样,在服务间调用时,token就会被传递下去。
评论已关闭