Spring Cloud学习笔记7-Feign(媒婆与金莲简单关系升级)

开发套路放在前:
a 加依赖

b 加注解

c 写配置


简介

Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可帮助我们更加便捷、优雅地调用HTTP API。

在Spring Cloud中,使用Feign非常简单——只需创建接口,并在接口上添加注解即可。

 

  • 依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 编写UserService接口(Feign Client)
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import sam.zeng.entity.User;

@FeignClient("providerService")
public interface UserService {
	@GetMapping("/users/{id}")
	User findById(@PathVariable("id") Long id);
}
  • 启动类上添加@EnableFeignClients,不加怎么让怎么生成UserService的代理?
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class ConsumerApp {

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

}
  • controller层注入UserService,可以抛弃RestTemplate了
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import sam.zeng.entity.User;
import sam.zeng.service.UserService;

@RequestMapping("/users")
@RestController
public class UserController {
	@Autowired
	private UserService userService;

	@GetMapping("/{id}")
	public User findById(@PathVariable Long id) {
		return userService.findById(id);
	}
}

return userService.findById(id);

就像本地调用一样,是不是很爽?但是feign比RestTemplate性能要差那么一点点,就像我比各位都帅那么一点点一样。。。。。。

你以为会让你爽太久?NO!

发现的问题:

如果服务提供者都挂了怎么办?如何容错?

且听下回吹牛B。。。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值