这里要写的是springboot 订单模块的服务去调用商品模块的服务进行下单操作
下面首先进行订单模块的代码编写
1、将order订单模块注册到注册中心
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8181/eureka
spring:
application:
name: eureka-client-orders
server:
port: 8185
2、pom.xml文件中添加
springcloud的feign依赖和
springboot的web依赖项
springcloud负载均衡的ribbon依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3、在主类中创建负载均衡的restTemplate字段
package pafc.cloud.eurekaclientorder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class EurekaClientOrderApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientOrderApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
4、微服务之间的调用,使用restTemplate进行调用
package pafc.cloud.eurekaclientorder.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import pafc.cloud.eurekaclientorder.domain.GoodItem;
import pafc.cloud.eurekaclientorder.domain.Order;
import pafc.cloud.eurekaclientorder.service.OrderService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class OrderServiceImpl implements OrderService {
@Autowired
public RestTemplate restTemplate;
@Override
public Object createOrder() {
Object allGoods = restTemplate.getForObject("http://eureka-client-goods/queryGoods/allGoods", Object.class);
Order orderItem = new Order();
List<Object> goodsLists = new ArrayList<Object>();
Map<String, GoodItem> allGoodsMap = (Map<String, GoodItem>) allGoods;
for (Map.Entry<String, GoodItem> item : allGoodsMap.entrySet()) {
goodsLists.add(item.getValue());
}
orderItem.setGoodsList(goodsLists);
orderItem.setId("001");
orderItem.setName("第一单");
orderItem.setPrice(98880.0);
return orderItem;
}
}
5、测试调用