前言:
在上一节里,我们学习了ribbon的使用。
我们了解到ribbon是一个客户端负载均衡机制。
而我们今天要讲的Feign呢,也是一款客户端负载均衡机制。
或者这样说,Feign封装了ribbon的负载均衡,实现了面向接口调用服务编程取缔面向服务编程。
ribbon面向服务编程:
@GetMapping("/hello")public ListsayHello() { List list = new ArrayList<>(); for(int i=0;i<30;i++) { list.add(restTemplate.getForObject("http://CL-HELLO-PRODUCER/hello", String.class)); } return list;}
feign面向接口编程:
@FeignClient(value="CL-HELLO-PRODUCER")public interface HelloService { @GetMapping("/hello") public String sayHello();}
新建一个服务消费者(cl_hello_consumer_feign):
1.添加依赖
4.0.0 com.xm.cloud cl_hello_consumer_feign 0.0.1-SNAPSHOT jar cl_hello_consumer_feign This is a Web about springcloud org.springframework.boot spring-boot-starter-parent 2.0.6.RELEASE UTF-8 UTF-8 1.8 Finchley.SR2 org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin
2.修改配置
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/eureka.client.register-with-eureka=false
3.开启注解
package com.xm.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.openfeign.EnableFeignClients;import org.springframework.context.annotation.ComponentScan;@EnableFeignClients@EnableDiscoveryClient@SpringBootApplicationpublic class ClHelloConsumerFeignApplication { public static void main(String[] args) { SpringApplication.run(ClHelloConsumerFeignApplication.class, args); }}
4.添加Service
package com.xm.cloud.service;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;@FeignClient(value="CL-HELLO-PRODUCER")public interface HelloService { @GetMapping("/hello") public String sayHello();}
5.添加Controller
package com.xm.cloud.controller;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import com.xm.cloud.service.HelloService;@RestControllerpublic class HelloController { @Autowired private HelloService helloService; @GetMapping("/hello") public ListsayHello() { List list = new ArrayList (); for(int i=0;i<10;i++) { list.add(helloService.sayHello()); } return list; }}
6.测试
访问:
0 | "Hello Spring Cloud! 001号机器" |
---|---|
1 | "Hello Spring Cloud! 003号机器" |
2 | "Hello Spring Cloud! 002号机器" |
3 | "Hello Spring Cloud! 001号机器" |
4 | "Hello Spring Cloud! 003号机器" |
5 | "Hello Spring Cloud! 002号机器" |
6 | "Hello Spring Cloud! 001号机器" |
7 | "Hello Spring Cloud! 003号机器" |
8 | "Hello Spring Cloud! 002号机器" |
9 | "Hello Spring Cloud! 001号机器" |