天天看点

spring-cloud之fegin

fegin它是用来做微服务之间的服务调用的,在使用fegin的时候直接调用微服务名称,fegin会去注册中心列表获取微服务,在获取到微服务之后,根据rebbion策略进行调用微服务,这边直接做具体实现了。

导入jar:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
           

启动类添加fegin使用注解:

@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients //使用@feign
public class ConsumeFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumeFeignApplication.class, args);
    }
}

           

创建service服务使用fegin调用其他的微服务

@FeignClient(value = "servce-feign",configuration = FeignClientsConfiguration.class,fallback = FeignServiceImpl.class)
public interface FeignService {
    @GetMapping("/order/getOrder")
    public Map<String,Object> getOrder(@RequestParam("id") Integer id);

    @PostMapping("/order/updateOrder")
    public OrderEntity updateOrder(@RequestBody OrderEntity orderEntity);

}
           

@FeignClient中value是调用那个微服务的名称,configuration 使用那个配置这里我们使用默认配置,这样我们的feign使用就算是完成了,我们可以通过控制层直接调用FeignService就可以看到具体效果了。

feign在调用的使用如何输出日志:

在feign的默认配置中它的日志级别为NONE不输出日志,这样不方便我们日常问题的排查,我们可以重写feign的日志方法:

@Configuration
public class FeignConfigure {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

}
           

配置不同的日志级别:

NONE :不记录任何日志(默认)

BASIC:仅记录请求方法、URL、响应状态代码以及执行时间

HEADERS:记录BASIC级别的基础上,记录请求和响应的header

FULL:记录请求和响应的header,body和元数据

同时我们需要在yml中添加配置:

logging:
  level:
    #控制FeignClient的日志输出,指向的是你需要输出日志的feign接口服务
     com.study.service.FeignService: DEBUG
           

最后我们修改@FeignClient中configuration配置中指向的配置类就可以了。