前提
-
zookeeper以及dubbo已經安裝並啓動
-
項目是在原來的基礎上創建的
創建一個新的模塊fbs-service,步驟如下:
創建fbs-service模塊
在pom.xml中添加依賴:
<dependency>
<groupId>net.wanho.fenbushi</groupId>
<artifactId>fbs-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
修改pom.xml中的build標籤如下:
<build>
<finalName>fbs-service</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<path>/</path>
<port>8081</port>
</configuration>
</plugin>
</plugins>
</build>
在該模塊的的src/main下面加入java文件夾,設置爲Sources Root,在該文件夾下創建com.elvis.service.impl包,在包下面加入UserServiceImpl.java類。
package com.elvis.service.impl;
import com.elvis.pojo.User;
import com.elvis.service.UserService;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Override
public List<User> queryUsers() {
List<User> list = new ArrayList<>();
//這裏面查詢數據庫並不是我們關注的主要矛盾
list.add(new User(1,"ali"));
list.add(new User(2,"zhangli"));
list.add(new User(3,"xiaoli"));
return list;
}
}
在該模塊的的src/main下面加入resources文件夾,設置爲Resources Root,在該文件夾下創建applicationContext-service.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:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<context:component-scan base-package="net.wanho.fenbushi.service"></context:component-scan>
<!-- 發佈dubbo服務 -->
<dubbo:application name="fenbushi-service"/>
<!-- 提供依賴信息,這是我們zookeeper的地址 -->
<dubbo:registry protocol="zookeeper" address="192.168.100.192:2181" />
<!-- 暴露一個服務在20880端口 -->
<dubbo:protocol name="dubbo" port="20882"/>
<!-- 暴露一個實際服務,ref是接口實現類的首字母小寫而成 -->
<dubbo:service interface="net.wanho.fenbushi.service.UserService" ref="userServiceImpl" timeout="30000"/>
</beans>
修改src/main/webapp/WEB-INF/web.xml,配置父容器即可
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-service.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
項目結構如下:
項目結構
8、啓動以及測試
以tomcat插件方式啓動
打開瀏覽器,輸入http://192.168.4.201:8080/dubbo,按如下步驟操作:
測試
我們看到,服務的生產者已經有了,缺少消費者,下面我們就創建web層,即服務消費者。