栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springcloud学习笔记:通过RestTemplate调用微服务接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springcloud学习笔记:通过RestTemplate调用微服务接口

         本文主要介绍如何在springcloud中通过RestTemplate实现微服务接口调用,以及负载均衡配置。本例使用的springcloud版本为:2021.0.3,springboot版本为:2.6.8。

1、创建消费端项目

        打开idea新建项目,选择maven,创建springboot项目consumer-order。

2、pom文件配置

        在项目pom中引入如下依赖:


    org.springframework.boot
    spring-boot-starter-web
 


    org.projectlombok
    lombok



    groupId>org.springframework.cloud
    spring-cloud-starter-netflix-eureka-client
    3.1.3
 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 create(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommentResult.class);
    }

    @GetMapping("/get/{id}")
    CommentResult 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中进行接口调用测试:

 


新时代农民工 (QQ:277718357) 点击关注下方↓微信公众号:程序进阶之路,了解更多技术知识。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1024015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号