当前位置: 首页 > news >正文

远程调用基本实现

1.配置文件

RestTemplate:是 Spring Framework 提供的一个用于同步调用 HTTP 接口的客户端工具类,主要用于在 Java 应用中发起 HTTP 请求(如 GET、POST 等)并处理响应。

package com.cx.order.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;/*** @author Jiang* @date 2025/11/7*/
@Configuration
public class OrderConfig {@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}
}

2.OrderServiceImpl

package com.cx.order.service.impl;import com.cx.Order;
import com.cx.Product;
import com.cx.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;/*** @author Jiang* @date 2025/11/7*/
@Service
public class OrderServiceImpl implements OrderService {@AutowiredDiscoveryClient discoveryClient;@AutowiredRestTemplate restTemplate;@Overridepublic Order createOrder(Long userId, Long productId) {Product product = getProductFromRemote(productId);Order order = new Order();order.setId(1L);// 总金额=价格*数量BigDecimal price = product.getPrice();//价格int num = product.getNum();//数量order.setTotalAmount(price.multiply(new BigDecimal(num)));//总价order.setUserId(userId);order.setNickName("张三");order.setAddress("火星");// 远程查询商品列表order.setProductList(Arrays.asList(product));return order;}//远程调用获取商品信息public Product getProductFromRemote(Long productId) {//1、获取到商品服务所在的所有机器IP+portList<ServiceInstance> instances = discoveryClient.getInstances("service-product");ServiceInstance instance = instances.get(0);//远程URLString url = "http://" + instance.getHost() + ":" + instance.getPort() + "/productId/" + productId;//2、给远程发送请求return restTemplate.getForObject(url, Product.class);}
}
http://www.dtcms.com/a/581982.html

相关文章:

  • 上海微网站制作建设网页设计心得300
  • 网站视频与服务器的关系html网页制作颜色代码
  • 北京亦庄信创产业链闭环初成,下一站是“生态质量”
  • 【uniapp】小程序体积优化,分包异步化
  • 如何做出好的产品:黑客马拉松产品核心逻辑[特殊字符]
  • 网站注入木马crm管理系统登录
  • Vue 2 和 Vue 3 的区别
  • 【FPGA】使用移位实现LED流水灯
  • Arbess零基础学习 - 使用Arbess+GitLab+Hadess实现Java项目自动化构建/主机部署/上传制品
  • S12 简单排序算法--冒泡 选择 直接插入 希尔排序
  • 【RabbitMQ】工作模式实现
  • 自己做淘宝优惠券网站旅游网站模板html免费下载
  • 进一步强化网站建设wordpress用户权限在哪改
  • 【Android Studio】Android Studio的安装过程以及初步使用
  • [人工智能-大模型-138]:如何把文本语言转化成词向量,然后作为模型的输入?给出中间每个步骤的输入和输出的实例值。
  • [Linux]学习笔记系列 -- [kernel]cpu
  • 河南建设工程信息网站怎么自己做游戏软件的app
  • 公司做网站是做什么账务处理传奇网页版在线玩
  • 西门子PLC扩展模块连接兼容性详解
  • 手机使用过的痕迹能查到吗?完整查询指南与步骤
  • Python 类继承详解:深度学习神经网络架构的构建艺术
  • 网站域名申请怎么做wordpress七牛云图床插件
  • 界面控件DevExpress WPF v25.1新版亮点:数据管理功能全新升级
  • 张家港专业的网站制作公司建设部职称网站
  • C# AutoResetEvent和ManualResetEvent
  • AI驱动半导体良率提升:基于机器学习的晶圆缺陷分类系统搭建
  • 系统架构师·案例分析相关知识点
  • 建站公司前景网站运营有前途吗
  • Leetcode 48
  • 因需写了个内网运维专用的IP地址管理工具,有点不同