目录
- 介绍
- 实现
- 提供统一业务api
- 服务提供者
- 1.导入依赖
- 2添加dubbo配置
- 3编写并暴露服务
- 服务消费者
- 1.导入依赖
- 2添加dubbo配置
- 3引用服务
- 测试
介绍
Dubbo是阿里巴巴开源的基于 Java 的高性能 RPC分布式服务框架,致力于提供高性能和透明化的 RPC远程服务调用方案,以及SOA服务治理方案。
Spring-cloud-alibaba-dubbo 是基于SpringCloudAlibaba技术栈对dubbo技术的一种封装,目的在于实现基于RPC的服务调用。
实现
提供统一业务api
在shop-common中ProductService,商品与订单服务都会调用它
public interface ProductService {Product findByPid(Integer pid);
}
shop-common的实体类都实现序列化接口
服务提供者
1.导入依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-dubbo</artifactId></dependency>
2添加dubbo配置
dubbo:scan:base-packages: com.itheima.service.impl # 开启包扫描,使暴漏接口注解能被扫描到protocols:dubbo:name: dubbo # 服务协议port: -1 # 服务端口 不限制的意思registry:address: spring-cloud://localhost # 注册中心 会注册到nacos
3编写并暴露服务
//暴露服务 注意这里使用的是dubbo提供的注解@Service,而不是Spring的
@Service
public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductDao productDao;@Overridepublic Product findByPid(Integer pid) {return productDao.findById(pid).get();}
}
服务消费者
1.导入依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-dubbo</artifactId></dependency>
2添加dubbo配置
dubbo:registry:address: spring-cloud://localhost # 注册中心cloud:subscribed-services: service-product # 订阅的提供者名称
3引用服务
@RestController
@Slf4j
public class OrderController {@Autowiredprivate OrderService orderService;//服务引用@Referenceprivate ProductService productService;@RequestMapping("/order/prod/{pid}")public Order order(@PathVariable Integer pid) {log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", pid);//调用商品微服务,查询商品信息Product product = productService.findByPid(pid);log.info("查询到{}号商品的信息,内容是:{}", pid, JSON.toJSONString(product));//下单(创建订单)Order order = new Order();order.setUid(1);order.setUsername("测试用户");order.setPid(pid);order.setPname(product.getPname());order.setPprice(product.getPprice());order.setNumber(1);orderService.createOrder(order);log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));return order;}}
测试
先启动服务提供者,再启动服务消费者,然后浏览器访问测试