Spring Cloud(三) 服务消费(Ribbon)

一、建一个服务消费者

 新建一个项目,命名为hello-service-ribbon

pom.xml依赖如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <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-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

二、配置application.properties

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=hello-service-ribbon
server.port=8083

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

@SpringBootApplication
@EnableDiscoveryClient
public class HelloServiceRibbonApplication {

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


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

编写测试类HelloService,代码如下:

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    public String helloService(String name){
        return restTemplate.getForObject("http://HELLO-SERVICE/hi?name="+name,String.class);
    }
}

再编写一个controller,如下:

@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

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

hello-service中的代码如下:

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class HelloServiceApplication {

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

    @Value("${server.port}")
    String port;
    @RequestMapping("/hi")
    public String home(@RequestParam String name) {
        return "hi "+name+",i am from port:" +port;
    }
}

在浏览器上多次访问http://localhost:8083/hi?name=zhao,浏览器交替显示:

hi zhao,i am from port:8081

hi zhao,i am from port:8082


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值