Windows下dubbo环境搭建及初步使用
一、dubbo简介
Dubbo是阿里巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和Spring框架无缝集成。
二、环境准备
本案例使用环境:jdk(1.8)、maven(3.2+)、zookeeper(3.4.10)、eclipse(Oxygen.3a Release (4.7.3a))、tomcat(tomcat8)
a、搭建注册中心(jdk、maven、tomcat、eclipse集成可以自行搜索安装)
1、本次实例使用zookeeper作为注册中心,下载地址:http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.10/zookeeper-3.4.10.tar.gz
也可以去官网下载想要的版本,官网地址:http://zookeeper.apache.org/releases.html
2、解压 zookeeper-3.4.10.tar.gz,进入解压后conf目录下,复制zoo_sample.cfg文件,重命名为zoo.cfg即可
3、进入解压后bin目录,点击zkServer.cmd即可
b、搭建dubbo-admin控制台(可选)
1、下载源码安装 ,下载地址:https://github.com/apache/incubator-dubbo/tree/dubbo-2.5.8
也可以选择下载对应的版本。
2、解压后,打开cmd进入dubbo-admin目录下,如我解压的目录为:D:\Test\dubbo-master\dubbo-admin,在cmd下输入命令:mvn clean install
3、在target目录下生成dubbo-admin-2.5.8.war,然后将该war包放入tomcat的webapps目录下,启动tomcat, 访问localhost:[端口]/dubbo-admin-2.5.8,输入默认的用户名和密码:root/root
例如我访问的地址为:http://localhost:8088/dubbo-admin-2.5.8/
三、基于步骤二搭建的环境,使用ide开发JavaEE项目
a、新建一个maven父项目dubbo-demo-master,和三个maven子模块dubbo-demo-interface、dubbo-demo-service、dubbo-demo-web(不知道如何新建百度搜索:eclipse搭建maven多module项目)
1、完成后,添加相关项目依赖和插件,最后其dubbo-demo-master的pom.xml内容为(该maven工程packaging属性为pom),删除该工程的src目录(父工程不需要,只管理依赖):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-master</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <name>dubbo-demo-master</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <springVersion>4.3.0.RELEASE</springVersion> <dubboVersion>2.5.8</dubboVersion> <zkclientVersion>0.10</zkclientVersion> <zookeeperVersion>3.4.10</zookeeperVersion> <slf4jVersion>1.7.21</slf4jVersion> <mybatisVersion>3.4.4</mybatisVersion> <mybatisSpringVersion>1.3.0</mybatisSpringVersion> <mysqlVersion>6.0.5</mysqlVersion> <druidVersion>1.1.6</druidVersion> <junitVersion>4.12</junitVersion> <jacksonVersion>2.9.3</jacksonVersion> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junitVersion}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springVersion}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatisSpringVersion}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatisVersion}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druidVersion}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4jVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>${zkclientVersion}</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>${zookeeperVersion}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>${dubboVersion}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> <modules> <module>dubbo-demo-interface</module> <module>dubbo-demo-service</module> <module>dubbo-demo-web</module> </modules> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <charset>${project.build.sourceEncoding}</charset> <server>tomcat7</server> </configuration> </plugin> </plugins> </build> </project>
2、完成后,其dubbo-demo-interface的pom.xml文件内容为(该maven工程packaging属性jar):
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-master</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>dubbo-demo-interface</artifactId> <name>dubbo-demo-interface Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> </dependencies> <build> <finalName>dubbo-demo-interface</finalName> </build> </project>
3、完成后,添加dubbo-demo-interface依赖,其dubbo-demo-service的pom.xml文件内容为(该maven工程packaging属性为war):
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-master</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>dubbo-demo-service</artifactId> <packaging>war</packaging> <name>dubbo-demo-service Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-interface</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <exclusions> <exclusion> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> </dependencies> <build> <finalName>dubbo-demo-service</finalName> </build> </project>
4、完成后,添加dubbo-demo-interface依赖,其dubbo-demo-web的pom.xml文件内容为(该maven工程packaging属性为war):
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-master</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>dubbo-demo-web</artifactId> <packaging>war</packaging> <name>dubbo-demo-web Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.moy.maven</groupId> <artifactId>dubbo-demo-interface</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <exclusions> <exclusion> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> </dependencies> <build> <finalName>dubbo-demo-web</finalName> </build> </project>
5、打开cmd进入dubbo-demo-master的pom.xml同级目录,执行mvn clean install ,其他子工程同理
b、编辑dubbo-demo-interface工程,新增服务接口UserService和实体User,删除必要文件(如:webapp文件),修改完成后在pom.xml目录下使用命令:mvn clean install
package org.moy.maven.service; import java.util.List; import org.moy.maven.domain.User; public interface UserService { /** * 查询所有用户 * @return */ List<User> findAll(); /** * 根据主键查询用户 * @param userId * @return */ User get(Integer userId); /** * 新增用户 * @param user */ void add(User user); /** * 根据主键删除用户 * @param user */ void delete(User user); /** * 修改用户 * @param user */ void update(User user); }
package org.moy.maven.domain; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = 1L; private Integer id; private String username; private String password; private String email; private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
c、更新dubbo-demo-service的maven项目,编辑dubbo-demo-service工程,webapp只留下web.xml,删除不必要的jsp文件
1、BaseMapper
package com.moy.maven.mapper; import java.io.Serializable; import java.util.List; public interface BaseMapper<E, P extends Serializable> { /** * 新增 * @param entity * @return */ P insert(E entity); /** * 根据主键刪除记录 * @param pk * @return */ Integer delete(P pk); /** * 更新实体记录 * @param entity * @return */ Integer update(E entity); /** * 根据实体内容查询实体列表 * @param entity * @return */ List<E> select(E entity); /** * 根据主键查询实体 * @param pk * @return */ E get(P pk); /** * 根据实体内容查询总数 * @param entity * @return */ Integer count(E entity); }
2、UserMapper
package com.moy.maven.mapper; import org.moy.maven.domain.User; public interface UserMapper extends BaseMapper<User, Integer> { }
3、UserServiceImpl
package com.moy.maven.service.impl; import java.util.List; import org.moy.maven.domain.User; import org.moy.maven.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.moy.maven.mapper.UserMapper; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findAll() { return userMapper.select(null); } @Override public User get(Integer userId) { return userMapper.get(userId); } @Override public void add(User user) { userMapper.insert(user); } @Override public void delete(User user) { userMapper.delete(user.getId()); } @Override public void update(User user) { userMapper.update(user); } }
4、UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.moy.maven.mapper.UserMapper"> <resultMap type="user" id="userResultMap"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="password" property="password" /> <result column="email" property="email" /> <result column="address" property="address" /> </resultMap> <insert id="insert" keyProperty="id" parameterType="user"> insert into t_user(username,password,email,address) values(#{username},#{password},#{email},#{address}) </insert> <delete id="delete" parameterType="int"> delete from t_user WHERE id=#{id} </delete> <update id="update" parameterType="user"> update t_user set username=#{username},password=#{password},email=#{email},address=#{address} WHERE id=#{id} </update> <select id="select" parameterType="user" resultMap="userResultMap"> select * from t_user <where> <if test="id != null"> and id = #{id} </if> <if test="username != null"> and username like #{username} </if> <if test="email != null"> and email like #{email} </if> <if test="address != null"> and address like #{address} </if> </where> </select> <select id="get" parameterType="int" resultMap="userResultMap"> select * from t_user where id=#{id} </select> <select id="count" parameterType="user" resultType="integer"> select count(0) from t_user <where> <if test="id != null"> and id = #{id} </if> <if test="username != null"> and username like #{username} </if> <if test="email != null"> and email like #{email} </if> <if test="address != null"> and address like #{address} </if> </where> </select> </mapper>
5、app.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/whymoy?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC jdbc.username=xxx jdbc.password=xxx
6、import.sql
CREATE TABLE t_user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(255) DEFAULT NULL, password varchar(255) DEFAULT NULL, email varchar(255) DEFAULT NULL, address varchar(255) DEFAULT NULL, PRIMARY KEY (id) );
7、log4j.properties
###set log levels### log4j.rootLogger=info, stdout ###输出到控制台### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n
8、mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置全局属性 --> <settings> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --> <setting name="useGeneratedKeys" value="true" /> <!-- 使用列别名替换列名 默认:true --> <setting name="useColumnLabel" value="true" /> <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} --> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <typeAliases> <package name="org.moy.maven.domain" /> </typeAliases> </configuration>
9、spring-dao.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- *** dataSource start *** --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- === dataSource end === --> <!-- 配置mybatis的sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mappers.xml文件 --> <property name="mapperLocations" value="classpath:mappers/*.xml"></property> <!-- mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.moy.maven.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
10、spring-dubbo-provider.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" 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"> <dubbo:application name="dubbo-user-service" /> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:service interface="org.moy.maven.service.UserService" ref="userService" version="1.0.0" /> </beans>
11、spring-tx.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- *** transactionManager start *** --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- === transactionManager end === --> <!-- *** 配置事务增强处理Bean,指定事务管理器 start *** --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" propagation="REQUIRED"/> <tx:method name="load*" read-only="true" propagation="REQUIRED"/> <tx:method name="find*" read-only="true" propagation="REQUIRED"/> <tx:method name="list*" read-only="true" propagation="REQUIRED"/> <tx:method name="count*" read-only="true" propagation="REQUIRED"/> <tx:method name="query*" read-only="true" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="execute*" propagation="REQUIRED"/> <tx:method name="copy*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- === 配置事务增强处理Bean,指定事务管理器 end === --> <!-- *** 配置一个切入点 start *** --> <aop:config> <aop:pointcut id="defaultPointcut" expression=" execution(* com.moy.*.*.mapper.*Dao.*(..)) || execution(* com.moy.*.*.mapper.*Support.*(..)) || execution(* com.moy.*.*.mapper.*Service.*(..)) || execution(* com.moy.*.*.mapper.*Impl.*(..)) || execution(* com.moy.*.*.mapper.impl.*impl.*(..)) || execution(* com.moy.*.*.support.*Support.*(..)) || execution(* com.moy.*.*.support.*Impl.*(..)) || execution(* com.moy.*.*.support.impl.*Impl.*(..)) || execution(* com.moy.*.*.service.*Service.*(..)) || execution(* com.moy.*.*.service.*Impl.*(..)) || execution(* com.moy.*.*.service.impl.*Impl.*(..)) "/> <aop:advisor advice-ref="txAdvice" pointcut-ref="defaultPointcut"/> </aop:config> <!-- === 配置一个切入点 end === --> <!-- *** 开启事务控制的注解支持 start *** --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- === 开启事务控制的注解支持 end === --> </beans>
12、spring.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="com.moy" /> <context:property-placeholder location="classpath:app.properties"/> <import resource="spring-dubbo-provider.xml"/> <import resource="spring-dao.xml"/> <import resource="spring-tx.xml"/> </beans>
13、UserMapperTest.java
package com.moy.maven.mapper; import java.util.List; import java.util.Random; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.moy.maven.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring.xml") public class UserMapperTest { @Autowired private UserMapper userMapper; @Test public void insertTest() { User user = createRandomUser(); Assert.assertTrue(userMapper.insert(user) == 1); Assert.assertTrue(user.getId() > 0); } @Test public void deleteTest() { User user = createRandomUser(); Assert.assertTrue(userMapper.insert(user) == 1); Assert.assertTrue(userMapper.delete(user.getId()) == 1); } @Test public void updateTest() { User user = createRandomUser(); Assert.assertTrue(userMapper.insert(user) == 1); Assert.assertNotNull(user.getPassword()); user.setPassword(null); Assert.assertTrue(userMapper.update(user) == 1); Assert.assertNull(user.getPassword()); } @Test public void selectTest() { List<User> list = userMapper.select(null); System.out.println(list); } @Test public void getTest() { User user = createRandomUser(); Assert.assertTrue(userMapper.insert(user) == 1); User queryUser = userMapper.get(user.getId()); Assert.assertTrue(user.getPassword().equals(queryUser.getPassword())); } @Test public void countTest() { Integer count = userMapper.count(null); System.out.println(count); } public static User createRandomUser() { User user = new User(); Random random = new Random(); user.setUsername("用戶" + random.nextInt(1000)); user.setEmail(random.nextInt(1000) + "@qq.com"); user.setPassword(String.valueOf(random.nextInt(1000))); user.setAddress(String.format("第%s星球", random.nextInt(1000))); return user; } }
14、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- *** 初始化Spring容器开始 *** --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <!-- === 初始化Spring容器结束 === --> </web-app>
15、测试,创建app.properties配置的数据库和导入import.sql,运行UserMapperTest单元测试,如果出错就看日志定位。
d、更新dubbo-demo-web的maven项目,编辑dubbo-demo-web工程,webapp只留下web.xml,删除不必要的jsp文件
1、UserController.java
package com.moy.maven.controller; import java.util.List; import org.moy.maven.domain.User; import org.moy.maven.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @RequestMapping("/list") @ResponseBody public List<User> listUser() { List<User> userList = userService.findAll(); return userList; } }
2、log4j.properties
###set log levels###
log4j.rootLogger=info, stdout
###输出到控制台###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{dd/MM/yy hh:mm:ss:sss z}] %t %5p %c{2}: %m%n
3、spring-dubbo-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" 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"> <dubbo:application name="dubbo-user-web" /> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:reference id="userService" interface="org.moy.maven.service.UserService" version="1.0.0" /> </beans>
4、spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" 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://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <context:component-scan base-package="com.moy" /> <import resource="spring-dubbo-consumer.xml" /> </beans>
5、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> <!-- *** 编码拦截器开始(拦截器加载有顺序,放在最前面) *** --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- === 编码拦截器结束 === --> <!-- *** 初始化SpringMVC开始 *** --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- === 初始化SpringMVC结束 === --> </web-app>
6、index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> hello world! </body> </html>
四、集成测试
1、确保zookeeper是启动的
2、打开cmd进入dubbo-demo-master的pom.xml同级目录下,运行命令:mvn clean install
3、打开cmd进入dubbo-demo-service的pom.xml同级目录下,运行命令:mvn clean tomcat:run -Dmaven.tomcat.port=8098
4、打开cmd进入dubbo-demo-web的pom.xml同级目录下,运行命令:mvn clean tomcat:run -Dmaven.tomcat.port=8099
5、打开浏览器访问:http://localhost:8099/dubbo-demo-web/users/list.do接口,(接口数据是运行UserMapperTest单元测试来的)
6、dubbo-demo-service工程实现接口,运行时向zookeeper注册接口信息,dubbo-demo-web工程只需要依赖接口,在通过spring原有的方式调用接口,其中dubbo帮我们从zookeeper中查找相应接口信息,通过默认dubbo协议帮我们完成了rpc调用。可以通过控制台http://localhost:8088/dubbo-admin-2.5.8/查看对应服务,对服务进行治理。
yexiangyang
moyyexy@gmail.com