第二篇:服务提供与Rest+Ribbon调用

在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是Ribbon+RestTemplate,另一种是Feign(Feign默认集成了ribbon)

什么是Ribbon

ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon

ribbon 默认实现的配置bean:

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: NoOpPing
  • ServerList ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

 

本篇基上一篇的工程

创建服务的消费者

先建一个model,service-ribbon工程,同时引入ribbon依赖、eureka client依赖

<!--Eureka依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--Web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Ribbon依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

编写配置文件application.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon

在启动类上增加@EnableEurekaClient,@EnableDiscoveryClient注解

通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean:restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能

@SpringBootApplication
@EnableEurekaClient
public class ServiceRibbonApplication {

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

编写一个测试类HelloService,通过之前注入IOC容器的restTemplate来消费eureka-client服务的“/test”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://eureka-client/test?name=" + name, String.class);
    }

}

写一个controller,在controller中用调用HelloControler的方法

@RestController
public class HelloControler {

    @Autowired
    HelloService helloService;

    @GetMapping(value = "/hi")
    public String hi(@RequestParam String name) {
        return helloService.hiService(name);
    }
}

依次启动eureka-server,service-client,service-ribbon,其中eureka-client项目启动2个,这时你会发现:service-client在eureka-server注册了2个实例,这就相当于一个小的集群

可能有些人不知如何一个项目开启多个,小编就和大家说说
在启动编辑里,选择右上角的Allow parablel run,点击应用,这样就一个项目开启多个了(启动多个同一个服务时,端口不能一样,需要修改)

 

然后在浏览器上多次访问http://localhost:8764/hi?name=haha,浏览器交替显示

hi haha ,现在的端口是:8762
hi haha ,现在的端口是:8763

 

源码:https://gitee.com/niugit_admin/spring-cloud-finchley

posted @ 2020-03-07 13:07  如何下笔呢  阅读(575)  评论(0编辑  收藏  举报
levels of contents