fegin需要实现类_Fegin

a7860942db9461fc27f8b609a89e56b8.png

Fegin客户端

什么是Fegin,Fegin是一个声明式的Http客户端,它使得写Http客户端变得更简单,使用Fegin只需要创建一个接口并注解,它具有可插拔的注解特性,Nacos很好的兼容了Fegin,默认实现了负载均衡的效果,底层使用了HttpClient作为服务框架

创建项目

打开之前创建的工程Nacos,目前已经有两个子工程:

  • nacos-provide:服务提供者
  • nacos-consumer:服务消费者(RestTemplate+Ribbon服务调用)

同样的操作,在Nacos项目下继续创建一个Springboot项目名为nacos-feign,创建时添加OpenFeign的依赖,如图:

nacos-fegin的pom.xml文件如下:

<?

创建RemoteClient接口,来定义OpenFeign要调用的远程服务接口。

同时通过@FeginClient注解指定被调用方的服务名,通过fallback属性指定RemoteHystrix类,来进行远程调用的熔断和降级处理。

RemoteClient.java代码如下

@FeignClient(name = "nacos-provide",fallback = RemoteHystrix.class)
public interface RemoteClient {

    @GetMapping("/helloNacos")
    String helloNacos();
}

RemoteHystrix.java代码如下

@Component
public class RemoteHystrix implements RemoteClient {
    @Override
    public String helloNacos() {
        return "请求超时了";
    }
}

通过OpenFeign调用远程服务

在启动类NacosFeignApplication.java中添加注解@EnableDiscoveryClient开启服务注册、添加注解@EnableFeignClients开启OpenFeign,启动类通过OpenFeign调用服务代码如下

@SpringBootApplication
@RestController
@EnableDiscoveryClient
@EnableFeignClients
public class NacosFeignApplication {

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

    @Autowired
    private RemoteClient remoteClient;

    @GetMapping("/feign")
    public String test() {
        return remoteClient.helloNacos();
    }
}

添加项目配置文件

在resourse目录下,添加application.yml配置

server:
  port: 9529

spring:
  application:
    name: nacos-feign
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

启动测试

  1. 启动项目nacos-provide
  2. 启动项目nacos-feign

浏览器访问 http://127.0.0.1:9529/feign, 可以看到返回结果与RestTemplate结果无异,但对于编码和操作方式都更加优雅。

访问nacos-feign的接口 http://127.0.0.1:9529/feign, 可以通过OpenFeign远程调用nacos-provide的接口,返回结果:

b005028dde2172b785e0b68035ccdd3e.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值