IDEA 中构建Spring Cloud内部服务调用Ribbon(二)
本文是基于 IDEA 中构建Spring Cloud注册和服务发现中心(一)的基础上进行的添加和修改
创建Module,client1
1,在src.main.java包下新建文件夹client1
2,在client1下创建启动服务主类:Client1Application
package client1;
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.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class Client1Application {
public static void main(String[] args) {
SpringApplication.run(Client1Application.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
3,在client1下创建调用内部服务的消费者测试类:TestController.java
package client1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value = "/client1")
public class TestController {
@Autowired
RestTemplate restTemplate;
@RequestMapping("/hi")
public String hi(@RequestParam String id){
// url中第一个service1为调用服务类注册时的名称,后面是请求地址
String url = "http://service1/service1/hi?id="+id;
return restTemplate.getForObject(url, String.class);
}
}
4,在resource文件夹下创建配置文件:application.yml
spring:
application:
name: client1
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8081/eureka/
server:
port: 6001
5,在 IDEA 中构建Spring Cloud注册和服务发现中心(一)中的路由配置文件中注册client1
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8081/eureka/
spring:
application:
name: gateway
server:
port: 8084
zuul:
routes:
service1: /service1/**
client1: /client1/**
6,输入测试地址:
http://localhost:6001/client1/hi?id=234
http://localhost:8084/client1/client1/hi?id=234