Spring Cloud Alibaba 使用RestTemplate進行服務消費
阿新 • • 發佈:2021-11-02
建立服務提供者工程
建立spring-cloud-alibaba-service-member工程,會員中心服務該服務提供使用者會員資訊。
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gitee</groupId> <artifactId>spring-cloud-alibaba-service-member</artifactId> <version>0.0.1</version> <dependencyManagement> <dependencies> <!-- spring boot 依賴 --> <dependency> <groupId>com.gitee</groupId> <artifactId>spring-cloud-alibaba-version-parent</artifactId> <version>${project.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- 公共模組 --> <dependency> <groupId>com.gitee</groupId> <artifactId>spring-cloud-alibaba-common</artifactId> <version>${project.version}</version> </dependency> <!-- web服務 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- undertow伺服器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <!-- 引數校驗 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!-- nacos 服務治理 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- nacos 配置中心 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!-- 負載均衡 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> <!-- 使用 bootstrap --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bootstrap</artifactId> </dependency> </dependencies> </project>
MemberServiceApplication.java 啟動類
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.web.bind.annotation.RestController; /** * 會員中心服務啟動類 * * @author wentao.wu */ @RestController @EnableDiscoveryClient @SpringBootApplication public class MemberServiceApplication { public static void main(String[] args) { SpringApplication.run(MemberServiceApplication.class, args); } }
Bootstrap.yaml
server: port: 8081 spring: application: name: service-member cloud: nacos: discovery: server-addr: localhost:8848 metadata: version: 0.0.1 appname: ${spring.application.name} #指定名稱空間 對應dev環境 namespace: 7e3699fa-09eb-4d47-8967-60f6c98da94a #指定分組 案例組 group: EXAMPLE-GROUP #指定叢集環境 華南 cluster-name: HuaNan config: server-addr: localhost:8848 #指定名稱空間 對應dev環境 namespace: 7e3699fa-09eb-4d47-8967-60f6c98da94a #指定分組 案例組 group: EXAMPLE-GROUP #指定叢集環境 華南 cluster-name: HuaNan #指定配置檔案的型別,預設是properties file-extension: properties #字首${spring.application.name} prefix: service-user
MemberInfoController.java 會員資訊獲取介面
/**
* 會員資訊介面
*
* @author wentao.wu
*/
@RestController
@RequestMapping("/member/info")
public class MemberInfoController {
/**
* 獲取使用者會員資訊
*
* @param username
* @return
*/
@GetMapping("/getUserMember/{username}")
public Response<Map<String, Object>> getUserMember(@PathVariable("username") String username) {
Response<Map<String, Object>> response = new Response<>();
response.setCode("1");
response.setMsg("獲取會員資訊成功!");
//從資料庫根據使用者查詢會員資訊
Map<String, Object> result = new HashMap<>();
result.put("level", "vip1");
result.put("username", username);
response.setResult(result);
return response;
}
}
使用RestTemplate進行消費
使用前面文章建立的使用者中心服務spring-cloud-alibaba-service-user進行服務消費。
增加RestTemplate注入配置
RestTemplateConfig.java
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* RestTample配置
*/
@Configuration
public class RestTemplateConfig {
/**
* 注入RestTample模板並且開啟負載均衡
*/
@Bean
@LoadBalanced
public RestTemplate getRestTample(){
return new RestTemplate();
}
}
獲取使用者資訊同時包含使用者會員資訊
增加RestTamplteConsumerController.java
import java.util.HashMap;
import java.util.Map;
/**
* rest template consumer
*
* @author wentao.wu
*/
@RestController
@RequestMapping("/rest/consumer")
public class RestTamplteConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/getUserInfo/{username}")
public Response<Map<String, Object>> getUserInfo(@PathVariable("username") String username) {
// 通過的負載均衡介面獲取服務例項資訊
ServiceInstance serviceInstance = loadBalancerClient.choose("service-member");
String url = "http://" + serviceInstance.getServiceId() + ":" + serviceInstance.getPort() + "/member/info/getUserMember/" + username;
String result = restTemplate.getForObject(url, String.class);
Response<Map<String, Object>> response = (Response<Map<String, Object>>) JSONObject.parse(result);
Map<String,Object> userinfo = new HashMap<>();
userinfo.put("userage","100");
userinfo.put("email","[email protected]");
response.getResult().putAll(userinfo);
response.setMsg("獲取使用者資訊成功!");
return response;
}
}
請求使用者服務獲取資訊:http://localhost:8080/rest/consumer/getUserInfo/zhangsan 返回值為
{
"code": "1",
"msg": "獲取會員資訊成功!",
"errorCode": null,
"errorMsg": null,
"result": {
"level": "vip1",
"userage": "100",
"email": "[email protected]",
"username": "zhangsan"
}
}
以上程式碼通過負載均衡客戶端獲取到會員服務的一個例項並且使用例項的ip與埠拼接成一個請求路徑,並且帶上具體訪問的請求地址對會員服務進行請求,請求到會員資訊後將會員資訊與使用者資訊合併返回到前端。
原始碼程式碼存放地址
gitee: https://gitee.com/SimpleWu/spring-cloud-alibaba-example.git
cnblogs: https://www.cnblogs.com/SimpleWu
持續更新目錄:https://www.cnblogs.com/SimpleWu/p/15476427.html