天天看點

springcloud_2021.0.3學習筆記:通過RestTemplate調用微服務接口

本文主要介紹如何在springcloud中通過RestTemplate實作微服務接口調用,以及負載均衡配置。本例使用的springcloud版本為:2021.0.3,springboot版本為:2.6.8。

1、建立消費端項目

打開idea建立項目,選擇maven,建立springboot項目consumer-order。

springcloud_2021.0.3學習筆記:通過RestTemplate調用微服務接口

2、pom檔案配置

在項目pom中引入如下依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
 
<dependency>
    groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>3.1.3</version>
</dependency>           

3、application.yml檔案配置

在項目resources檔案夾下建立application.yml檔案,并按如下内容進行配置:

server:
  port: 80
 
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka
    fetch-registry: true
  instance:
    instance-id: consumer-order-${server.port}
    prefer-ip-address: true
 
spring:
  application:
    name: consume-order           

4、主應用類配置

在項目src/main/java下建立主應用類 ConsumerOrderApplication.java,添加eureka服務端注解@EnableEurekaServer和@SpringBootApplication。

@EnableEurekaClient
@SpringBootApplication
public class ConsumerOrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerOrderApplication.class, args);
    }
}           

5、RestTemplate配置

建立配置類ApplicationContextConfig,并指定用于傳回RestTemplate的bean。注解@LoadBalanced用于在調用微服務接口時進行負載均衡。

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;
 
@Configuration
public class ApplicationContextConfig {
 
    @Bean
    @LoadBalanced
    RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}           

6、controller層調用

在controller層可以通過RestTemplate進行微服務接口調用,使用方法如下:

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private RestTemplate restTemplate;
 
    private final String PAYMENT_URL = "http://PAYMENT-SERVER";
 
    @PostMapping("/create")
    CommentResult<Integer> create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommentResult.class);
    }
 
    @GetMapping("/get/{id}")
    CommentResult<Payment> getById(@PathVariable(name = "id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommentResult.class);
    }
}           

7、測試驗證

同時啟動并運作項目eueka-server-7001、eueka-server-7002、payment-8001、payment-8002、consumer-order。然後在postman中進行接口調用測試:

springcloud_2021.0.3學習筆記:通過RestTemplate調用微服務接口

繼續閱讀