Rumah > Java > javaTutorial > teks badan

spring cloud2.0学习笔记之Feign实战

无忌哥哥
Lepaskan: 2018-07-20 12:02:45
asal
3373 orang telah melayarinya

背景

  • springCloud:Finchley.RELEASE

简介

Feign是SpringCloud体系中声明式Rest客户端,通过简单配置、创建接口和注解即可实现Restful服务的调用。而且开始支持SpringMvc了。

简单应用

  • 依赖:org.springframework.cloud:spring-cloud-starter-openfeign

  • 入口加@EnableFeignClients注解

  • 创建相应接口、加注解 

//入口类
@SpringBootApplication
@EnableFeignClientspublic class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
//原型接口声明
@FeignClient("stores")public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();    
    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
Salin selepas log masuk

开启Feign断路器和上下文支持

  • feign.hystrix.enabled=true

# To disable Hystrix in Feignfeign:
  hystrix:
    enabled: true# To set thread isolation to SEMAPHORE# 将断路器隔离级别由默认的线程隔离调整为信号灯hystrix:
  command:    default:
      execution:
        isolation:
          strategy: SEMAPHORE
Salin selepas log masuk

断路器回调

断路器支持回退,就是当断路器开启或接口出现错误时执行回调定义的方法,返回预先定义好的结果。 开启回调支持只需在@FeignClient注解中配置fallback参数为接口的回调实现类,并且回调实现类要被注解为Spring Bean(可以通过@Component,@Service等注解实现,详情见Spring4的注解文档)。

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Componentstatic class HystrixClientFallback implements HystrixClient {
    @Override    
    public Hello iFailSometimes() {        
        return new Hello("fallback");
    }
}
Salin selepas log masuk

如果需要知道回退原因可以通过回退工厂来实现,代码实例如下:

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

@Componentstatic class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
    @Override    public HystrixClient create(Throwable cause) {        
        return new HystrixClient() {
            @Override            
            public Hello iFailSometimes() {                
                return new Hello("fallback; reason was: " + cause.getMessage());
            }
        };
    }
}
Salin selepas log masuk

Feign支持继承接口

Feign支持接口继承的方式,将操作通过接口来形成契约。

//生产者的控制层接口public interface UserService {

    @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
    User getUser(@PathVariable("id") long id);
}
//生产者的控制器实现
@RestController
public class UserResource implements UserService {}
//消费端的Feign接口定义
package project.user;
@FeignClient("users")
public interface UserClient extends UserService {}
Salin selepas log masuk

压缩支持

开启压缩可以有效节约网络资源,但是会增加CPU压力,建议把最小压缩的文档大小适度调大一点

//开启压缩
feign.compression.request.enabled=true
feign.compression.response.enabled=true

//配置压缩文档类型及最小压缩的文档大小
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048
Salin selepas log masuk

日志配置

  • 消费服务的接口所在包,必须是debug

# 日志支持logging.level.project.user.UserClient: DEBUG
Salin selepas log masuk
  • 定义自定义配置类,定义日志级别

@Configurationpublic class FooConfiguration {
    @Bean
    Logger.Level feignLoggerLevel() {        
        return Logger.Level.FULL;
    }
}
Salin selepas log masuk
  • 日志级别

    • NONE, No logging (DEFAULT).

    • BASIC, Log only the request method and URL and the response status code and execution time.

    • HEADERS, Log the basic information along with request and response headers.

    • FULL, Log the headers, body, and metadata for both requests and responses.

Atas ialah kandungan terperinci spring cloud2.0学习笔记之Feign实战. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan