SpringCloud使用Feign消费服务

Feign简介

       Spring Cloud Feign是基于Netflix Feign实现,整合了Spring Cloud Riggon与Spring Cloud Hystrix,出了提供这两者的强大功能外,他还提供了一种声明式的web服务客户端定义方式。
       在使用Spring Cloud Ribbon时,通常都会利用它对RestTemplate的请求拦截来实现对服务的调用,而RestTemplate已经实现了对http请求的封装处理,形成了一套模板的调用方法。

快速使用

       在pom文件中添加对feign的依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>   

在启动类中使用注解开启Feign的功能:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OwlBookstoreWebApiApplication {

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

创建调用接口,使用注解来消费服务

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;

import cn.net.bysoft.owl.bookstore.facade.user.entity.User;
import cn.net.bysoft.owl.bookstore.web.api.fallback.UserServiceFallbackFactory;

@FeignClient(value = "https://my.oschina.net/u/2450666/blog/SERVICE-USER", fallbackFactory = UserServiceFallbackFactory.class)
public interface UserService {

    @RequestMapping(value = "https://my.oschina.net/users/{email}/", method = RequestMethod.GET)
    Boolean isExistsByEmail(@PathVariable("email") String email);

    @RequestMapping(value = "https://my.oschina.net/users/{id}", method = RequestMethod.GET)
    User findById(@PathVariable("id") Long id);

}

接口中声明的方法的参数与返回值,要与服务提供的方法一致。
Feign自动开启了Ribbon中的负载均衡和hystrix断路器,要使用断路器先需要开启断路器:

feign:
  hystrix:
    enabled: true
  compression:
    request:
      enabled: true
    response:
      enabled: true

在Feign中使用的是fallbackFatory来降级服务,使用该方式可以同时处理服务抛出的异常,创建一个UserServiceFallbackFactory类:

mport org.springframework.stereotype.Component;

import cn.net.bysoft.owl.bookstore.facade.user.entity.User;
import cn.net.bysoft.owl.bookstore.web.api.service.UserService;
import feign.hystrix.FallbackFactory;

@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserService> {

    @Override
    public UserService create(Throwable cause) {
        return new UserService() {

            @Override
            public Boolean isExistsByEmail(String email) {
                system.out.println(cause.getmessage());
                return false;
            }

            @Override
            public User findById(Long id) {
                cause.printStackTrace();
                System.out.println(cause.getMessage());
                return null;
            }

        };
    }

}

Feign配置

Ribbon配置

全局配置的方法:

ribbon.ConnectTimeout=500
ribbon.ReadTimeout=5000

猜你喜欢

转载自blog.csdn.net/liuziteng0228/article/details/81058329