创建消费者
工程结构
配置consumer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<context:component-scan base-package="com.accp.gmall.service.impl" />
<!-- 指定当前应用/服务的名字 -->
<dubbo:application name="order-service-consumer"></dubbo:application>
<!-- 指定注册中心的位置 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry>
<!-- 声明需要调用的远程服务的接口;生成远程服务代理 -->
<dubbo:reference interface="com.accp.gmall.service.UserService" id="userService"/>
</beans>
需要调用远程服务的接口是提供者暴露的服务:
<dubbo:service interface="com.accp.gmall.service.UserService" ref="userService"/>
远程调用实现:OrderServiceImpl
import com.accp.gmall.bean.UserAddress;
import com.accp.gmall.service.OrderService;
import com.accp.gmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private UserService userService;
public void initOrder(String userId) {
//1、查询用户的收货地址
List<UserAddress> userAddressList = userService.getUserAddressList("1");
System.err.println(userAddressList.toString());
}
}
启动程序:
import com.accp.gmall.service.OrderService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
public class MainApplication {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("consumer.xml");
OrderService orderService = classPathXmlApplicationContext.getBean(OrderService.class);
orderService.initOrder("1");
System.in.read();
}
}
运行成功:
dubbo管理控制台显示: