springcloud入门之服务消费者(ribbon)

来源:互联网 发布:浪潮软件股票 编辑:程序博客网 时间:2024/06/07 02:04

之前搭建的注册中心:http://blog.csdn.net/chenhaotao/article/details/78677328
服务提供者client:http://blog.csdn.net/chenhaotao/article/details/78677858

再简单搭建一个基于ribbon实现服务调用的服务消费者

1.创建一个springboot项目ribbon,依赖选择spring-cloud-starter-eureka、spring-cloud-starter-ribbon、web

        <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>

ribbon是一个负载均衡客户端

2.在application.yml中配置服务名称端口和注册中心地址

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

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

@SpringBootApplication@EnableDiscoveryClientpublic class ServiceRibbonApplication {    public static void main(String[] args) {        SpringApplication.run(ServiceRibbonApplication.class, args);    }    @Bean    @LoadBalanced    RestTemplate restTemplate(){        return new RestTemplate();    }}

4.创建service,使用@Autowired注入RestTemplate并使用RestTemplate调用注册中心服务

@Servicepublic class TestService {    @Autowired    RestTemplate restTemplate;    public  String testService(String name){        return restTemplate.getForObject("http://SERVICE-HI/index?name="+name,String.class);    }}

5.编写controller类注入service并调用相应方法测试服务调用

@RestControllerpublic class TestController {    @Autowired    TestService testService;    @RequestMapping("/test")    public String test(@RequestParam String name){        return testService.testService(name);    }}

6.启动注册中心eureka-server,再启动服务eureka-client ,再启动服务消费 service-ribbon
url输入:http://localhost:1111 可以查看到注册中心多了一个名为 SERVICE-HELLO的服务
url输入:http://localhost:8081/index?name=aaa 查看服务client是否正常
url输入:http://localhost:9001/test?name=aaa 测试服务消费是否正常调用服务

项目源码:https://pan.baidu.com/s/1b28q8u

阅读全文
0 0