天天看点

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调用微服务接口

继续阅读