springcloud使用使用Feign-Ribbon做负载均衡实现声明式REST调用

什么是Feign

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。注意:负载均衡是加在客户端中,而不是服务端中。

简而言之:

Feign 采用的是基于接口的注解

Feign 整合了ribbon

代码实现及演示效果

注册中心(略)

1、在客户端添加依赖包

1
2
3
4
< dependency >
     < groupId >org.springframework.cloud</ groupId >
     < artifactId >spring-cloud-starter-feign</ artifactId >
</ dependency >

2、在客户端启动类中使用@EnableFeignClients开启feiginClient功能

1
2
3
4
5
6
7
8
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public  class  ServiceAApplication {
     public  static  void  main(String[] args) {
         SpringApplication.run(ServiceAApplication. class , args);
     }
}

3、在客户端中新建一个ServiceAFeignClient接口调用service-b的服务

1
2
3
4
5
6
7
8
9
10
11
package  com.example.servicea;
import  org.springframework.cloud.netflix.feign.FeignClient;
import  org.springframework.stereotype.Component;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestParam;
@Component
@FeignClient (value =  "service-b" //这里的name对应调用服务的spring.applicatoin.name
public  interface  ServiceAFeignClient {
     @RequestMapping (value =  "/hi" )
     String hi( @RequestParam ( "id" ) String id);
}

4、在客户端系统中写一个测试controller

1
2
3
4
5
6
7
8
9
10
@RestController
public  class  TestController {
     @Autowired
     ServiceAFeignClient serviceAFeignClient;
     
     @RequestMapping ( "/hi" )
     public  String hi( @RequestParam  String id){
         return  serviceAFeignClient.hi(id);
     }
}

5、在服务端系统中提供一个hi()方法,供客户端调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@EnableEurekaClient
@RestController
@SpringBootApplication
public  class  ServiceBApplication {
     public  static  void  main(String[] args) {
         SpringApplication.run(ServiceBApplication. class , args);
     }
     @Value ( "${spring.application.name}" )
     private  String name;
     @Value ( "${server.port}" )
     private  String port;
     @RequestMapping ( "/hi" )
     public  String hi( @RequestParam  String id){
         return  "hi, "  + id +  ", "  + name +  ":"  + port;
     }
}

6、新建一个服务service-b-2,代码和service-b完全一致,只需改端口号(服务名也叫service-b,spring.application.name=service-b

在eclipse中可以不新建工程,当启动了service-b后,改service-b的端口号,再启动一次,这样就启动了两个service-b服务,区别是端口号不同。

启动后会在Eureka注册中心中看到service-b有两个,一个端口号为8081,一个为8082:

DS Replicas

Instances currently registered with Eureka

Application AMIs Availability Zones Status
SERVICE-A n/a (1) (1) UP (1) - SZVY2AWX5511361.china.huawei.com:service-a:8083
SERVICE-B n/a (2) (2)

UP (2) - SZVY2AWX5511361.china.huawei.com:service-b:8081 ,

 SZVY2AWX5511361.china.huawei.com:service-b:8082

7、查看效果

访问:http://localhost:8083/hi?id=123

返回:hi, 123, service-b:8082

刷新:hi, 123, service-b:8081

刷新:hi, 123, service-b:8082

刷新:hi, 123, service-b:8081

因为Ribbon负债均衡默认使用的是轮询机制。

猜你喜欢

转载自www.cnblogs.com/xyhero/p/ce8b825bca3a5da1ea47aa0da163cd8b.html