开发套路放在前:
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性能要差那么一点点,就像我比各位都帅那么一点点一样。。。。。。
- 测试http://localhost:8081/users/3如下图,成功,爽歪歪
你以为会让你爽太久?NO!
发现的问题:
如果服务提供者都挂了怎么办?如何容错?
且听下回吹牛B。。。