一摆屯、代碼示例
說明:此處使用的SpringBoot版本為2.1.13.RELEASE敌厘,SpringCloud版本為Greenwich.SR5
SpringCloud消費(fèi)者以REST調(diào)用服務(wù)
1、maven依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2舌狗、application.yml
server:
port: 9001
spring:
application:
name: consumer
eureka:
instance:
hostname: localhost
prefer-ip-address: true
instance-id: consumer-9001
client:
service-url:
defaultZone: http://eureka7001:7001/eureka/,http://eureka7002:7002/eureka/,http://eureka7003:7003/eureka/
#info信息
info:
app:
name: consumer-9001
company:
name: www.xxx.com
build:
artifactId: ${project.artifactId}
version: ${project.version}
3叽奥、啟動(dòng)類
注入RestTemplate進(jìn)行調(diào)用,此處在啟動(dòng)類中進(jìn)行創(chuàng)建痛侍。
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class Consumer9001Application {
public static void main(String[] args) {
SpringApplication.run(Consumer9001Application.class,args);
}
@Bean
RestTemplate restTemplate(){
return new RestTemplate();
}
}
4朝氓、其他java類
在Controller類型注入RestTemplate,并通過RestTemplate進(jìn)行REST調(diào)用主届。RestTemplate可以注入到其他Bean類型赵哲,此處為了方便演示放在了Controller中。
package org.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class HelloController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello/{name}")
public String hello(@PathVariable String name){
return restTemplate.getForObject("http://localhost:8001/hello/"+name,String.class);
}
}
2君丁、測(cè)試驗(yàn)證
先后啟動(dòng)server枫夺、client和consumer服務(wù),訪問http://localhost:7001/可以看到client和consumer都已經(jīng)注冊(cè)到了eureka绘闷。
image.png
訪問http://localhost:9001/hello/zs
image.png
表明consumer成功調(diào)用了client提供的服務(wù)橡庞。
github:
https://github.com/panli1988/cloud01
https://github.com/panli1988/cloud02
參考:
https://blog.csdn.net/forezp/article/details/70148833
http://www.itmuch.com/spring-cloud/spring-cloud-index/
還有尚硅谷周陽老師的視頻