服务消费者(ribbon)

pom文件包含依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

application.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/  //指向服务注册中心
server:
  host: 8764
spring:
  application:
    name: service-ribbon

声明服务发现,注入RestTemplate,启用负载均衡

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableDiscoveryClient  //向服务中心注册
@SpringBootApplication
public class RibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run(RibbonApplication.class, args);
    }
    
    @Bean
    @LoadBalanced  //开启负载均衡
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Service

import org.springframework.stereotype.Service;

@Service
public class RibbonService {

    @Autowired
    RestTemplate restTemplate;
    
    public String ribbonService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name, String.class);  //消费service-hi的hi接口,ribbon根据服务名选择具体的服务实例
    }
}

Controller

import com.aaron.ribbon.service.RibbonService;

@RestController
public class RibbonController {

    @Autowired
    RibbonService ribbonService;
    
    @RequestMapping(value="/hi")
    public String hi(@RequestParam String name) {
        return ribbonService.ribbonService(name);  //调用Service方法
    }
}

在浏览器访问http://127.0.0.1:8080/hi?name=jack,以负载均衡的方式访问多个服务实例。

posted @ 2018-04-25 17:06  AaronCnblogs  阅读(200)  评论(0)    收藏  举报