Ribbon 服务发现(Ribbon)

  1. 启动【服务中心】集群,即 Eureka Server
    localhost:/8081、
    localhost:/8082、
    localhost:/8083
    其实单机版也行...
    pom、启动类、yml文件

  2. 启动【服务提供者】集群 ,即Eureka Client
    localhost:/52601、
    localhost:/52602、
    localhost:/52603

  3. 创建【服务消费者】,即Eureka Discovery Client(Ribbon),本质使用RestTemplate

    • pom文件:

         
             org.springframework.boot
             spring-boot-starter-web
         
         
             org.springframework.cloud
             spring-cloud-starter-netflix-eureka-client
         
         
             org.springframework.cloud
             spring-cloud-starter-netflix-ribbon
          
      
    • 启动类:

      @SpringBootApplication
      @EnableDiscoveryClient        //启动Eureka服务发现的相关配置
      public class EurekaRibbonApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(EurekaRibbonApplication.class, args);
          }
      }
      
    • RestTemplate配置&&Service层&&Controller层

      配置类 EurekaRibbonConfig :

      @Configuration
      public class EurekaRibbonConfig {
          @Bean
          @LoadBalanced   //实现负载均衡
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      }
      

      业务层 EurekaRibbonService:

      @Service
      public class EurekaRibbonService {
      
          @Autowired
          RestTemplate restTemplate;
      
          public String getInfo() {
              System.out.println("调用服务    EUREKA-CLIENT/info");
      
              String message = restTemplate.getForObject("http://EUREKA-CLIENT/info", String.class);
      
              System.out.println("调用 EUREKA-CLIENT/info 返回信息: " + message);
              System.out.println("调用 EUREKA-CLIENT/info 成功!");
      
              return message;
          }
      }
      

      控制层 EurekaRibbonController

      @RestController
      public class EurekaRibbonController {
      
          @Autowired
          private EurekaRibbonService eurekaRibbonService;
      
          @RequestMapping("/ribbonInfo")
          public String ribbonInfo() {
              return "获取的信息:  " + eurekaRibbonService.getInfo();
          }
      }
      
    • 配置文件yml

      server:
        port: 52610
      spring:
        application:
          name: eureka-discovery-ribbon
      eureka:
        instance:
          hostname: localhost
          lease-renewal-interval-in-seconds: 5
          lease-expiration-duration-in-seconds: 10
        client:
          service-url:
            defaultZone: http://localhost:8081/eureka/,http://localhost:8082/eureka/,http://localhost:8083/eureka/
      

启动【服务消费者】工程
访问地址http://localhost:8081/、http://localhost:8082/、http://localhost:8083/
看到好东西了(【服务消费者】EUREKA-DISCOVERY-RIBBON成功注册到【服务中心】)


调用接口地址http://localhost:52610/ribbonInfo


多刷新几次,就能看到负载均衡的效果,即轮询请求了不同的【服务提供者】

【服务消费者】结束!!!

你可能感兴趣的:(Ribbon 服务发现(Ribbon))