Zookeeper的安装这里就不写了,可以百度一下(文末会附上工程源码

目录

一 工程结构

二 框架搭建

2.1 父工程

2.2 实体类模块

2.3 数据访问模块

2.4 接口模块

2.5 服务模块

2.6 控制层模块

2.7 逆向工程

三 测试

3.1 数据库表

3.2 后端代码

3.3 前端代码

3.4 结果展示

四 常见错误

4.1 注册中心找不到服务

4.2 无法连接到注册中心

五 源码下载


一 工程结构

工程说明:

demo-parent 为聚合工程

demo-dao 为数据库访问层

demo-pojo 为实体类

demo-xxx-interface  为xxx服务层的接口

demo-xxx-service 为xxx服务层的实现

demo-xxx-web 为web工程

后面可以根据自己的业务需求添加一些服务层和web层,比如有订单模块,那就可以添加

demo-order-interface,demo-order-service,demo-order-web 三个模块

二 框架搭建

2.1 父工程

创建 Maven 工程 demo-parent ,groupId 为 cn.demo ,artifactId 为demo-parent , 在 pom.xml 引入下面的依赖,下面的模块都继承自父工程

 <!-- 集中定义依赖版本号 -->
    <properties>
        <junit.version>4.12</junit.version>
        <spring.version>4.2.4.RELEASE</spring.version>
        <pagehelper.version>4.0.0</pagehelper.version>
        <servlet-api.version>2.5</servlet-api.version>
        <dubbo.version>2.8.4</dubbo.version>
        <zookeeper.version>3.4.7</zookeeper.version>
        <zkclient.version>0.1</zkclient.version>
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis.spring.version>1.2.2</mybatis.spring.version>
        <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
        <mysql.version>5.1.32</mysql.version>
        <druid.version>1.0.9</druid.version>


    </properties>

    <dependencyManagement>
        <dependencies>

            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jms</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- dubbo相关 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>dubbo</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <!--zookeeper-->
            <dependency>
                <groupId>org.apache.zookeeper</groupId>
                <artifactId>zookeeper</artifactId>
                <version>${zookeeper.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.sgroschupf</groupId>
                <artifactId>zkclient</artifactId>
                <version>${zkclient.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.9</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.28</version>
            </dependency>
            <dependency>
                <groupId>javassist</groupId>
                <artifactId>javassist</artifactId>
                <version>3.11.0.GA</version>
            </dependency>
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>1.10</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>${pagehelper.version}</version>
            </dependency>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis.spring.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.miemiedev</groupId>
                <artifactId>mybatis-paginator</artifactId>
                <version>${mybatis.paginator.version}</version>
            </dependency>
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>


        </dependencies>

    </dependencyManagement>



    <build>

        <plugins>
            <!-- java编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

        </plugins>

    </build>

2.2 实体类模块

 在demo-parent模块下创建实体类模块demo-pojo,并在java文件夹下创建包,包名为com.demo.pojo,包下的TbUser和TbUserExample会在2.7节用逆向工程讲解如何生成

2.3 数据访问模块

 这里有几个文件要配置下1.pom.xml 2 db.properties 3 SqlMapConfig.xml 4 applicationContext-dao.xml

1 pom.xml


    <dependencies>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.miemiedev</groupId>
            <artifactId>mybatis-paginator</artifactId>
        </dependency>
        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <!--引入实体类-->
        <dependency>
            <groupId>cn.demo</groupId>
            <artifactId>demo-pojo</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

2 db.properties

这里配置了一些数据库连接地址,端口号,以及指定的数据库,还有数据连接的账号和密码

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123

3 SqlMapConfig.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>
	<plugins>
		<!-- com.github.pagehelper 为 PageHelper 类所在包名 -->
		<plugin interceptor="com.github.pagehelper.PageHelper">
			<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL 六种数据库-->
			<property name="dialect" value="mysql"/>
		</plugin>
	</plugins>
</configuration>

4 applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 ">

    <!-- 数据库连接池 -->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath*:properties/*.properties"/>
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="${jdbc.url}"/><!--数据库连接地址,端口号,数据库名-->
        <property name="username" value="${jdbc.username}"/><!--数据库用户名-->
        <property name="password" value="${jdbc.password}"/><!--数据库密码-->
        <property name="driverClassName" value="${jdbc.driver}"/><!--数据库驱动-->
        <property name="maxActive" value="10"/>
        <property name="minIdle" value="5"/>
    </bean>

    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis的全局配置文件,可以自定义配置其他的文件 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
    </bean>
    <!--mapper文件扫描的配置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.demo.mapper"/>
    </bean>
</beans>

2.4 接口模块

 pom.xml文件引入下面依赖

<dependencies>
        <dependency>
            <groupId>cn.demo</groupId>
            <artifactId>demo-pojo</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

2.5 服务模块

需要修改的文件1 pom.xml 2 web.xml 3 applicationContext-service.xml 4 applicationContext-tx.xml

1 pom.xml引入依赖 

<packaging>war</packaging>

    <dependencies>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

        <!-- dubbo相关 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>
        <!--动态类库,与jdk自带的反射功能类似,但比反射功能更强大-->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
        </dependency>
        <!--zookepper-->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>
        <!--user接口-->
        <dependency>
            <groupId>cn.demo</groupId>
            <artifactId>demo-user-interface</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--dao层-->
        <dependency>
            <groupId>cn.demo</groupId>
            <artifactId>demo-dao</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- 指定端口 -->
                    <port>9001</port>
                    <!-- 请求路径 -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

2 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<!-- 加载spring容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<!--这里的*表示:会将本地的以及依赖进来dao层配置文件一起加载到spring容器-->
		<param-value>classpath*:spring/applicationContext*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

3 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: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:protocol name="dubbo" port="20881"></dubbo:protocol>
    <!--注册的名称-->
    <dubbo:application name="demo-user-service"/>
    <!--zookepper的注册地址和端口-->
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <!--配置注解扫描包-->
    <dubbo:annotation package="com.demo.user.service.impl"/>
    
</beans>

4 applicationContext-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: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/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
       ">
    <!-- 事务管理器  -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource" />  
    </bean>
    <!-- 开启事务控制的注解支持,开启这个,只需要在类上加上注解,下面每个方法就会收到事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

2.6 控制层模块

此步骤需要修改的文件 1 pom.xml 2 web.xml 3 springmvc.xml 

1 pom.xml

<packaging>war</packaging>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.demo</groupId>
            <artifactId>demo-user-interface</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!-- dubbo相关 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
        </dependency>
        <!--动态类库,与jdk自带的反射功能类似,但比反射功能更强大-->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
        </dependency>
        <!--zookeeper-->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.sgroschupf</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- 指定端口 -->
                    <port>9101</port>
                    <!-- 请求路径 -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

2 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">	
   <!-- 解决post乱码 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>	
	
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载-->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:spring/springmvc.xml</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
	
</web-app>

3 springmvc.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
       ">

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!--配置消息转换器-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="application/json"/>
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteDateUseDateFormat</value>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 引用dubbo 服务 -->
    <dubbo:application name="demo-user-web"/>
    <!--zookeeper的注册地址和端口号-->
    <dubbo:registry address="zookeeper://192.168.25.128:2181"/>
    <!--注解扫描-->
    <dubbo:annotation package="com.demo.user.controller"/>
</beans>

2.7 逆向工程

打开逆向工程,修改generatorConfig.xml配置文件,修改下图中,标红色框框的信息(逆向工程最后会附上下载地址

运行GeneratorSqlmap下的main函数,会的到 下图

将实体类拷贝到工程的pojo下,将mapper接口和xml文件拷贝到dao层下,到这里环境就配置好了,后面开始写后端代码和前端代码了 ,注意点:实体类都要实现序列化,因为是远程调用

三 测试

3.1 数据库表


SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL COMMENT '用户名',
  `password` varchar(100) DEFAULT NULL COMMENT '密码',
  `name` varchar(100) DEFAULT NULL COMMENT '姓名',
  `age` int(10) DEFAULT NULL COMMENT '年龄',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别,1男性,2女性',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `created` datetime DEFAULT NULL COMMENT '创建时间',
  `updated` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`user_name`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'zhangsan', '123456', '张三', '30', '1', '1984-08-08', '2014-09-19 16:56:04', '2014-09-21 11:24:59');
INSERT INTO `tb_user` VALUES ('2', 'lisi', '123456', '李四', '21', '2', '1991-01-01', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('3', 'wangwu', '123456', '王五', '22', '2', '1989-01-01', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('4', 'zhangwei', '123456', '张伟', '20', '1', '1988-09-01', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('5', 'lina', '123456', '李娜', '28', '1', '1985-01-01', '2014-09-19 16:56:04', '2014-09-19 16:56:04');
INSERT INTO `tb_user` VALUES ('6', 'lilei', '123456', '李磊', '23', '1', '1988-08-08', '2014-09-20 11:41:15', '2014-09-20 11:41:15');
INSERT INTO `tb_user` VALUES ('8', 'xiaofeng', '123456', '萧峰', '30', '1', '2018-06-25', '2018-06-25 18:42:25', '2018-06-25 18:42:25');
INSERT INTO `tb_user` VALUES ('12', 'zhendeshuai', '565656', '吴彦祖', '26', '1', '2018-06-26', '2018-06-26 14:55:59', '2018-06-26 15:12:12');
INSERT INTO `tb_user` VALUES ('14', 'jiumozhi', '123456', '鸠摩智', '30', '1', '2018-06-26', '2018-06-26 23:53:15', '2018-06-26 23:53:15');
INSERT INTO `tb_user` VALUES ('21', 'zhangsan1234', '12345', '杰克', '20', '1', '2000-01-01', '2018-07-07 21:50:26', '2018-07-07 21:50:26');
INSERT INTO `tb_user` VALUES ('22', 'zhangsanqwe1', '123455', '张三', '30', '1', '1999-02-25', '2018-07-07 21:51:20', '2018-07-07 21:51:20');

3.2 后端代码

后端主要编写1 UserService(接口层) 2 UserServiceImpl(实现层) 3 UserController层

1 UserService(接口层)

package com.demo.user.service;
import com.demo.pojo.TbUser;
import java.util.List;

public interface UserService {
    /**
     * 查询所有用户
     * @return
     */
    public List<TbUser> findUserList();

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    public TbUser findUser(String username);

    /**
     * 通过年龄段查询用户
     * @param start
     * @param end
     * @return
     */
    public List<TbUser> findUsersByAge(Integer start,Integer end);
}

2 UserServiceImpl(实现层)

这里实现类上面一定不能忘了加上@Service注解,而且是dubbo下的@Service

package com.demo.user.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.demo.mapper.TbUserMapper;
import com.demo.pojo.TbUser;
import com.demo.pojo.TbUserExample;
import com.demo.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private  TbUserMapper userMapper;
    @Override
    public List<TbUser> findUserList() {
        //传null就是查询所有
        List<TbUser> userList = userMapper.selectByExample(null);
        return userList;
    }
    @Override
    public TbUser findUser(String username) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(username);
        List<TbUser> userList = userMapper.selectByExample(example);
        //根据用户名查询出来肯定只有一条记录
        return userList.get(0);
    }
    @Override
    public List<TbUser> findUsersByAge(Integer start, Integer end) {
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        //添加年龄查询条件
        criteria.andAgeBetween(start,end);
        List<TbUser> userList = userMapper.selectByExample(example);
        return userList;
    }
}

3 UserController层

这里需要注意:注入UserService时,用dubbox的@Reference注解

package com.demo.user.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.demo.pojo.TbUser;
import com.demo.user.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/findList")
    public List<TbUser> findList() {
      return userService.findUserList();
    }

    @RequestMapping("/findUser")
    public TbUser findUser(String username){
        return userService.findUser(username);
    }

    @RequestMapping("/findUsersByAge")
    public List<TbUser> findUsersByAge(Integer start, Integer end){
        return userService.findUsersByAge(start,end);
    }
}

3.3 前端代码

在webapp下添加上面红色框框的文件,有1 angular.min.js(前端框架)2 base.js  3 userService.js  4 userController.js 5 user.html

base.js

var app=angular.module("demo",[]);//构建模块

userService.js

app.service("userService", function ($http) {//构建前端服务层

    this.findList = function () {
        return $http.get('user/findList.do');
    }

    this.findUser = function (username) {
        return $http.get('user/findUser.do?username=' + username);
    }

    this.findUsersByAge = function (start, end) {
        return $http.get('user/findUsersByAge.do?start=' + start + '&end=' + end);
    }
})

 userController.js

app.controller("userController",function ($scope,userService) {

    //查询所有用户
    $scope.findList=function () {
        userService.findList().success(function (response) {
            $scope.list=response;
        })
    }

    //根据用户名查询用户信息
    $scope.findUser=function (username) {
        userService.findUser(username).success(function (response) {
            $scope.entity=response;
        })
    }

    //根据年龄段查询用户
    $scope.findUsersByAge=function (start,end) {
        userService.findUsersByAge(start,end).success(function (response) {
            $scope.users=response;
        })
    }
})

user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户查询</title>
    <!--引入angularjs-->
    <script src="js/angularjs/angular.min.js"></script>
    <script src="js/base.js"></script>
    <script src="js/service/userService.js"></script>
    <script src="js/controller/userController.js"></script>
</head>

<body ng-app="demo" ng-controller="userController">
<!--查询所有用户信息-->
<input type="button" ng-click="findList()" value="查询所有用户信息">
<table >
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建时间</th>
        <th>更新时间</th>
    </tr>
    <!--遍历集合-->
    <tr ng-repeat="entity in list">
        <td>{{entity.id}}</td>
        <td>{{entity.userName}}</td>
        <td>{{entity.password}}</td>
        <td>{{entity.age}}</td>
        <td>{{entity.sex}}</td>
        <td>{{entity.birthday}}</td>
        <td>{{entity.created}}</td>
        <td>{{entity.updated}}</td>
    </tr>

</table>
<hr>
<!--根据用户名查询用户信息-->
请输入用户名:<input ng-model="username">
<input type="button" ng-click="findUser(username)" value="查询">
<table  >
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建时间</th>
        <th>更新时间</th>
    </tr>
    <tr>
        <td>{{entity.id}}</td>
        <td>{{entity.userName}}</td>
        <td>{{entity.password}}</td>
        <td>{{entity.age}}</td>
        <td>{{entity.sex}}</td>
        <td>{{entity.birthday}}</td>
        <td>{{entity.created}}</td>
        <td>{{entity.updated}}</td>
    </tr>
</table>
<hr>
<!--根据年龄段查询用户信息-->
年龄:从<input ng-model="start">到<input ng-model="end">
<input type="button" ng-click="findUsersByAge(start,end)" value="查询">
<table >
    <tr>
        <th>编号</th>
        <th>用户名</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建时间</th>
        <th>更新时间</th>
    </tr>
    <!--遍历集合-->
    <tr ng-repeat="entity in users">
        <td>{{entity.id}}</td>
        <td>{{entity.userName}}</td>
        <td>{{entity.password}}</td>
        <td>{{entity.age}}</td>
        <td>{{entity.sex}}</td>
        <td>{{entity.birthday}}</td>
        <td>{{entity.created}}</td>
        <td>{{entity.updated}}</td>
    </tr>
</table>
</body>
</html>

3.4 结果展示

首先,先启动user-service服务,再启动user-web,浏览器地址栏输入:http://localhost:9101/user.html

四 常见错误

4.1 注册中心找不到服务

java.lang.IllegalStateException: Failed to check the status of the service
com.demo.user.service.UserService. No provider available for the service
com.demo.user.service.UserService from the url
zookeeper://192.168.25.129:2181/com.alibaba.dubbo.registry.RegistryService

如果出现上面的错误的话,检查一下你的服务层代码是否添加了@service 注解,并且该注解的包一定是 com.alibaba.dubbo.config.annotation 包,不是org.springframework.stereotype.Service,这个地方极容易出错 

4.2 无法连接到注册中心

org.I0Itec.zkclient.exception.ZkTimeoutException: Unable to connect to zookeeper server within
timeout: 5000 org.I0Itec.zkclient.ZkClient.connect(ZkClient.java:876)

如果出现上面这个异常,检查下 注册地址和端口号有没有写错,以及看下zookeeper是否启动

五 源码下载

源码:

链接:https://pan.baidu.com/s/1pRMAaQqgr3ezHiK1yUXjow 密码:fmrr

逆向工程:

链接:https://pan.baidu.com/s/1sudm5xINAHKqVNzI7nwBgA 密码:ivpx

 

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐