微服务的服务生产,个别是应用 feign 和 rebion 调用服务提供,进行服务的生产,本文将实战应用代码解说服务的生产。
微服务环境的搭建
创立一个 springboot 我的项目,springboot 是将服务进行拆分的一个最小服务单位。
增加 maven 依赖
- 根本的maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
rebion 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>
feign 依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
feign依赖蕴含rebion依赖,如果想同时应用 feign 和 rebion 依赖,只须要援用feign 即可。
增加application.yml
spring: cloud: nacos: discovery: server-addr: 127.0.0.1:8848
增加Appcation.java启动类
@SpringBootApplication//将服务注册到注册核心@EnableDiscoveryClient//扫描和注册feign客户端bean定义@EnableFeignClientspublic class NacosConsumeApplication { public static void main(String[] args) { SpringApplication.run(NacosConsumeApplication.class, args); }}
其中 @EnableDiscoveryClient 将服务注册到注册核心,@EnableFeignClients 扫描和注册feign客户端bean定义。fegin bean定义是 @FeignClient。
服务调用 : feign 和 ribbon
1. feign
- 创立feign客户端
@FeignClient(value = "service-provider")public interface ProductClient { @GetMapping("/hello") String product(@RequestParam("name") String name);}
这里 @FeignClient 就是创立bean 给 @EnableFeignClients 扫描的注册。 @FeignClient 外面的配置 value 对应的是服务提供者的服务名称,@GetMapping外面的value对应服务提供者的 @GetMapping 门路。
这样做的益处是这里间接配置好门路和服务名称,不须要调用方做任何的配置。
- 创立申请调用 feign客户端
@RestControllerpublic class FeignController { //这个谬误是编译器问题。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。 @Autowired private ProductClient productClient; @GetMapping("/feign") public String feign(String name){ return productClient.product(name); }}
2. rebion
配置 RestTemplate bean
@Configurationpublic class RibbonConfig { @LoadBalanced @Bean public RestTemplate restTemplate(){ return new RestTemplate(); }}
调用服务
@RestControllerpublic class RibbonController { @Autowired private RestTemplate restTemplate; @GetMapping("/ribbon") public String ribbon(String name){ String result = restTemplate.getForObject("http://service-provider/hello?name="+name,String.class); return result; }}
feign 和 rebion 优缺点
- feign 配置比拟简单明了,配置好了 FeignClient,间接调用即可,不过后续有多余的配置。
- rebion每次都须要配置申请门路,它的长处在于间接调用即可,不要独自配置客户端。