Feign配置

一 默认配置

  • 解码器(Decoder):bean名称为feignDecoder,ResponseEntityDecoder类,

  • 编码器(Encoder):bean名称为feignEecoder,SpringEncoder类。

  • 日志(Logger): bean名称为feignLogger,Slf4jLogger类。

  • 注解翻译器(Contract): bean名称为feignContract,SpringMvcContract类。

  • Feign实例的创建者(Feign.Builder):bean名称为feignBuilder,HystrixFeign.Builder类。

  • Feign客户端(Client):bean名称为feignClient,LoadBalancerFeignClient类。

二 自定义注解翻译器

1 新定义一个注解

package org.crazyit.cloud.contract;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyUrl {

    String url();
    String method();
}

2 自定义注解翻译器

package org.crazyit.cloud.contract;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.springframework.cloud.netflix.feign.support.SpringMvcContract;

import feign.MethodMetadata;

public class MyContract extends SpringMvcContract {

    @Override
    protected void processAnnotationOnMethod(MethodMetadata data,
            Annotation annotation, Method method) {
        super.processAnnotationOnMethod(data, annotation, method);
        // 注解是MyUrl类型的,才处理
        if(MyUrl.class.isInstance(annotation)) {
            System.out.println("#############  这是自定义翻译器");
            MyUrl myUrl = method.getAnnotation(MyUrl.class);
            String url = myUrl.url();
            String httpMethod = myUrl.method();
            data.template().method(httpMethod);
            data.template().append(url);
        }
    }

}

3 编写配置类

package org.crazyit.cloud.contract;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Contract;

@Configuration
public class MyConfig {

    @Bean
    public Contract feignContract() {
        return new MyContract();
    }
}

4 接口类使用注解

package org.crazyit.cloud;

import org.crazyit.cloud.contract.MyUrl;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient("spring-feign-provider")
public interface HelloClient {

    @RequestMapping(method = RequestMethod.GET, value="/hello/{name}")
    String hello(@PathVariable("name") String name);
    
    
    @RequestMapping(method = RequestMethod.GET, value="/call/{id}")
    Police getPolice(@PathVariable("id") Integer id);
    
    @MyUrl(url = "/hellowd", method = "GET")
    String myHello();
} 

5 重构服务端的控制器

package org.crazyit.cloud;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PoliceController {

    @RequestMapping(value = "/call/{id}", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Police call(@PathVariable Integer id, HttpServletRequest request) {
        Police p = new Police();
        p.setId(id);
        p.setName("angus");
        p.setMessage(request.getRequestURL().toString());
        return p;
    }
    
    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    public String hello(@PathVariable String name) {
        return "Hello, " + name;
    }
    
    @RequestMapping(value = "/hellowd", method = RequestMethod.GET)
    public String helloWithOutArg() {
        return "Hello World";
    }
}

 

6 重构客户端的控制器

package org.crazyit.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    
    @Autowired
    private HelloClient helloClient;

    @RequestMapping(method = RequestMethod.GET, value="/router")
    public String router() {
        String result = helloClient.hello("angus");
        return result;
    }

    @RequestMapping(method = RequestMethod.GET, value="/police",
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Police getPolice() {
        Police p = helloClient.getPolice(1);
        return p;
    }
    
    @RequestMapping(method = RequestMethod.GET, value="/myhello")
    public String myHello() {
        return helloClient.myHello();
    }
}

7 测试

三 可选配置

  • Logger.Level:接口日志的记录级别,相当于调用了Fiegn.Builder的logLevel方法。

  • Retryer:重试处理器,相当于调用了Fiegn.Builder的retryer方法。

  • ErrorDecoder:异常解码器,相当于调用了Fiegn.Builder的errorDecoder方法。

  • Request.Options:设置请求的配置项,相当于调用了Fiegn.Builder的options方法。

  • Collection<RequestInterceptor>:设置请求拦截器,相当于调用了Fiegn.Builder的requestInterceptors方法。

四 配置多个拦截器

@Bean
public RequestInterceptor getRequestInterceptorsA() {
    return new RequestInterceptor() {
        public void apply(RequestTemplate template) {
            System.out.println("这是第一个请求拦截器");
        }            
    };
}

@Bean
public RequestInterceptor getRequestInterceptorsB() {
    return new RequestInterceptor() {
        public void apply(RequestTemplate template) {
            System.out.println("这是第二个请求拦截器");
        }            
    };
}

五 压缩配置

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Feign进行服务之间的调用时,可以通过配置开启Hystrix的熔断功能。如果服务不可用或者超过访问时间,就会触发Hystrix的fallback回调函数。要开启熔断配置,需要在服务消费者的pom文件中添加Hystrix的依赖。然后创建Feign的实现类,实现Feign中的方法,并在Feign接口的@FeignClient注解中加上fallback属性,值是Feign实现类的字节码文件。在主启动类上加上@EnableHystrix注解来允许Hystrix的使用。在配置文件中设置开启熔断功能,可以通过feign.hystrix.enabled=true来开启Feign的熔断功能。\[1\] Feign中的Hystrix配置如下: ``` feign: hystrix: enabled: true okhttp: enabled: true httpclient: enabled: false client: config: default: # 超时时间配置 connectTimeout: 10000 readTimeout: 10000 compression: request: enabled: true response: enabled: true # Hystrix配置 hystrix: command: default: execution: isolation: strategy: SEMAPHORE thread: timeoutInMilliseconds: 60000 shareSecurityContext: true ``` 以上是Feign中Hystrix的配置,可以根据实际需求进行相应的调整。\[3\] #### 引用[.reference_title] - *1* *3* [Spring Cloud Feign熔断配置](https://blog.csdn.net/Diandikongji/article/details/112747687)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [feign的熔断](https://blog.csdn.net/weixin_45893072/article/details/122972939)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值