springCould 常见组件feign使用

springCould 常见组件feign使用

feign是一个声明式的Web服务客户端.

feign:基于ribbon和hystrix的声明式服务调用组件.

作用:

跨域请求,feign结合eureka注册中心,把不同的服务项目注册到eureka中,通过feign客户端进行调用来解决负载均衡问题

首先在写案例之前我们要先准备一些使用feign必不可少的东西。

一、依赖

首先pom.xml中引入spring-cloud-starter-eureka和spring-cloud-starter-feign依赖,具体内容如下:

        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.cloud
            spring-cloud-starter-feign
        

二、开启Spring Cloud Feign的支持功能

@EnableFeignClients

三、配置文件

1、eureka配置

eureka:
  instance:
    prefer-ip-address: true 
  client:
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka 

2、 feign相关配置

spring:
  main:
    allow-bean-definition-overriding: true #允许多个feign接口
feign:
  hystrix:
    enabled: true # 开启使用熔断器
  client:
    config:
      default:
        connectTimeout: 10000 # 10s就超时
        readTimeout: 10000 # 10s就超时

四、下面就是具体的使用样例,如下

package com.test;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 测试
 *
 * @author yangzhenyu
 **/
@FeignClient(name = "test", fallbackFactory = TestClientFallBackFactory.class)
public interface TestClient {

    /**
     * 测试
     *
     * @param id 
     * @return String
     * @author yangzhenyu
     **/
    @RequestMapping(value = "/yzy/test", method = RequestMethod.POST)
    String test(String id);
}

其中@FeignClient注解绑定的服务名不区分大小写 

package com.test;

import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 测试微服务调用
 *
 * @author yangzhenyu
 **/
@Slf4j
@Component
public class TestClientFallBackFactory implements FallbackFactory {

    /**
     * 熔断对象
     */
    @Autowired
    private TestClientFallback testClientFallback;

    @Override
    public TestClient create(Throwable e) {
        log.error("调用【{}】错误", "TestClient", e);
        return testClientFallback;
    }
}
package com.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 测试微服务调用
 *
 * @author yangzhenyu
 **/
@Slf4j
@Component
public class TestClientFallback implements TestClient {

    /**
     * 容错处理
     */
    @Override
    public String test(String id) {
        log.error("调用测试接口异常,传参:【{}】", id);
        //断路由模式,帮助服务依赖中出现的延迟和为故障提供强大的容错机制
        return null;
    }
}

 

你可能感兴趣的:(JAVA)