SpringCloud实战二:服务消费者(rest+ribbon)

在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring Cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign,在这一篇文章首先讲解下基于 ribbon+rest

ribbon是一个负载均衡客户端,可以很好的控制http和tcp的一些行为

新建一个项目: application.yml 如下

server:
  port: 8080
  servlet:
    context-path: /
eureka:
  client:
    healthcheck:
      enabled: true   # 开启健康检查(依赖spring-boot-starter-actuator)
    registry-fetch-interval-seconds: 5  # 去拉取服务注册信息间隔(默认为30秒)
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: api-geteway
  cloud:
    config: false
#zuul:
#  routes:
#    api-a:
#      path: /api-a/**
#      url: http://localhost:9000/product/index/

 

package com.cloud.zuul.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/restTemplate")
    public String restTemplate() {
        return restTemplate.getForObject("http://PRODUCT/index/hello",String.class);
    }

}
package com.cloud.zuul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ZuulApplication {

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


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

}

 

在之前9000端口的服务名为product创建一个controller

@RestController
@RequestMapping("/index")
public class ProductController {


    @GetMapping("/hello")
    public String hello() {
        return "product say hello";
    }


}

在服务器访问 spring.application.name = API-GETEWAY 的项目路径

localhost:8080/restTemplate   返回结果如下

SpringCloud实战二:服务消费者(rest+ribbon)_第1张图片

实际调用的是9000端口项目的/index/hello的接口,测试成功。下一章开始服务消费者

 

你可能感兴趣的:(springcloud)