Spring Cloud 实战(三)将RestTemplate替换为OpenFeign

前两篇文章分别实战了Eureka的客户端、服务端以及Hystrix熔断、降级
Spring Cloud 实战(一)以eureka作为服务注册中心
Spring Cloud 实战(二)使用hystrix有效处理服务雪崩

然而这两篇文章中客户端相互调用的方式采用的是RestTemplate并用注解@LoadBalanced标注为负载均衡。

本篇就采用OpenFeign来调用其他的客户端。

OpenFeign:声明式Rest客户端

Feign是一个声明式 Web 服务客户端。它使编写 Web 服务客户端更容易。要使用 Feign,请创建一个接口并对其进行注释。它具有可插入的注释支持,包括 Feign 注释和 JAX-RS 注释。Feign 还支持可插拔的编码器和解码器。Spring Cloud 添加了对 Spring MVC 注释的支持,并支持使用HttpMessageConvertersSpring Web 中默认使用的注释。Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer,在使用 Feign 时提供负载均衡的 http 客户端。

使用Feign的时候没有任何调用http接口的感觉,调用方式就是调用本地自定义的Java函数,简洁、方便。

如何使用Feign?

添加dependency

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

启用Feign,在Application中使用 注解@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
@EnableFeignClients
public class PassengerApplication {
	public static void main(String[] args) {
		SpringApplication.run(PassengerApplication.class, args);
	}

	@Bean
	@LoadBalanced
	/**
	* 此时Resttemplate非必要
	*/
	RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

创建客户端Service

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

@FeignClient("onlinecar-driver")
public interface DriverService {
    @RequestMapping("/driver/do/{id}")
    String getDriverInfo(@PathVariable String id);
}

在Controller中调用Service


    @Autowired
    DriverService driverService;

    @RequestMapping("/do/{userId}")
    @HystrixCommand(
        fallbackMethod = "fallbackMethod",
        commandProperties = {
                @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
        }
    )
    public String doDriver(@PathVariable String userId){
        return driverService.getDriverInfo(userId);
//        String url = "http://onlinecar-driver/driver/do/"+userId;
//        return restTemplate.getForObject(url,String.class);
    }

就这样就可以调用其他客户端的接口了,非常简单。
在这里插入图片描述

使用感受

没有能力对这两个进行评价,只能通过至今的一些简单实战,以此说一下使用这两种方法的感受。

如果是使用RestTemplate的话,想要向OpenFeign可以直接调用方法,那还需要自己的封装代码。否则的话,就每次调用的时候都要写Url,也比较麻烦。

而OpenFeign使用起来的感觉调用Java jdk,如果需要调用其他的接口,也只需在Service中再增加相应的方法就好了。




以上,就是对OpenFeign进行的一些简单实战。
附上文档

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值