给feign的url增加get参数,实现验签功能

需求:

使用feign代替httpclient生成http代理时,需要给每个url后增加验签的三个参数,如appKey,sign,时间戳等,写法如下:

@FeignClient(url = "${url}/xxx",name = "xxxFeign")

实现 

1 写一个类继承feign.Client.Default并重写execute方法

import com.js.apiserver.util.endecryption.MD5Util;
import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

public class MyDefaultClient extends Client.Default {
    @Value("${app_key}")
    private String app_key;
    @Value("${app_secret}")
    private String app_secret;

    public MyDefaultClient() {
        super(null, null);
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 计算签名SIGN
        String sign = MD5Util.encrypByMd5Jar(timestamp + "#" + app_secret);
        String url = request.url()+"?timestamp="+timestamp+"&app_key="+app_key+"&sign="+sign;
        return super.execute(Request.create(request.httpMethod(),url,request.headers(),request.requestBody()), options);
    }
}

2 写一个配置类装配

import feign.Client;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

@Configuration
public class JsFeignClientAutoConfiguration {

    @Autowired
    private ObjectFactory messageConverters;

    @ConditionalOnMissingBean(name = "myHttpClient")
    @Bean("myHttpClient")
    @Primary
    @ConditionalOnProperty("app_key")
    public Client setClient(){
        return new MyDefaultClient();
    }
    @Bean
    @Primary
    @Scope("prototype")
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }

    @Bean
    @Primary
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }
}

 

你可能感兴趣的:(Spring,Cloud)