分布式系统开发-放弃接口拼接SpringCloud(IX)
系统架构设计
浏览:509 次

我们已经实现了从注册表获取服务,并调用服务以获取返回的数据,但现在我们按如下方式调用产品信息:
包com.felix.service;
导入com.felix.fegin.GoodsFeignClient;
进口com.felix.model.Goods;
导入com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.cloud.client.discovery.DiscoveryClient;
导入org.springframework.stereotype.Service;
导入org.springframework.web.client.RestTemplate;
/**
*由weistekweistek于2019/1/3创建。
*/
@服务
公共类GoodsService{
@自动连线
私有RestTemplate RestTemplate;
@自动连线
私有发现客户端发现客户端;
@自动连线
私人商品FeignClient商品Feign客户端;
//启用负载平衡后,restTemplate可以选择要访问的服务
@HystrixCommand(fallbackMethod=“findGoodsByIdServiceOffline”)
公共物品findGoodsById(长id){

字符串服务=“货物服务”;
字符串url=“http://”+service+“/goods/”+id;
return restTemplate.getForObject(url,Goods.class);
}
公共物品findGoodsByIdServiceOffline(长id){
退货新商品(id,“查询产品信息时出错”,“”,“,”,0.0F);
}
获得服务后,您仍然需要拼接网址和相应的接口来访问数据提供程序。有没有更好的方法来访问服务而不需要自己拼接?是的,它是Feign
Feign是一个声明性的web服务客户端,这使得编写web服务客户端更容易。使用Feign创建接口并对其进行注释。它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。SpringCloud向SpringMVC添加注释。Spring Web默认使用HttpMessageConverters,Spring Cloud集成了Ribbon和Eureka提供的负载平衡HTTP客户端Feign
我已经说过很多关于它是什么以及它能带来什么便利。别担心,让我给你看最终结果:
//启用负载平衡后,restTemplate可以选择要访问的服务
@HystrixCommand(fallbackMethod=“findGoodsByIdServiceOffline”)
公共物品findGoodsById(长id){
return goodsFeignClient.findGoodsById(id);
}
哎哟,很好。你在goodsFeignClient.findGoodsById做了拼接吗?不,这是怎么回事?
首先,在现有订单模块的pom.xml中引入Feign依赖项
<依赖关系>
依赖性>
注:我的SpringCloud版本是格林威治。RC2和早期版本的Feign引入了这种依赖关系
<依赖关系>

依赖性>
好的,像往常一样,在OrderApplication中启用Faign
包com.felix;
导入org.springframework.boot.SpringApplication;
导入org.springframework.boot.autoconfigure.SpringBootApplication;
导入org.springframework.cloud.client.discovery.EnableDiscoveryClient;
导入org.springframework.cloud.client.loadbalancer.loadbalancer;
导入org.springframework.cloud.netflix.hystrix.EnableHystrix;
导入org.springframework.cloud.openfeign.EnableFeignClients;
导入org.springframework.context.annotation.Bean;
导入org.springframework.web.client.RestTemplate;
@启用FeignClients
@启用Hystrix
@启用DiscoveryClient
@SpringBootapp
公共类OrderApplication{
@豆
@LoadBalanced//启用负载平衡
公共RestTemplate RestTemplate(){
返回新的RestTemplate();
}

public static void main(String[]args){