最简单的SpringMvc+Spring+Mybatis+Mysql+Dubbo案例

1.新建一个maven的web项目,项目结构和pom文件如下:


<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>com.ly.mock</groupId>
	<artifactId>MockServer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<mock.version>1.0.0-SNAPSHOT</mock.version>
		<spring.version>4.2.3.RELEASE</spring.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.5.3</version>
			<exclusions>
				<exclusion>
					<artifactId>spring</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
				<exclusion>
					<artifactId>log4j</artifactId>
					<groupId>log4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
				<exclusion>
					<artifactId>jms</artifactId>
					<groupId>javax.jms</groupId>
				</exclusion>
				<exclusion>
					<artifactId>mail</artifactId>
					<groupId>javax.mail</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.15</version>
		</dependency>
        
         <!--mysql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</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-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-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- mybatis-spring整合jar -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.3.0</version>
		</dependency>

		<!-- mybatis ORM框架 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.5</version>
			<type>pom</type>
		</dependency>

		<dependency>
			<groupId>com.101tec</groupId>
			<artifactId>zkclient</artifactId>
			<version>0.4</version>
		</dependency>
		
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.2</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.11</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.37</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>mock_server</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>



pom文件引入了SpringMvc+Spring+Mybatis+Dubbo+zookeeeper 这些框架的必要jar,值得注意的是之前一直没忽略dubbo中的spring的一些jar,导致SpringAop一直报错only available on JDK 1.5 and higher,原因是dubbo中的内置spring为2.5,而我本身用的jdk为1.8,所以屏蔽掉dubbo中的spring一些jar就可以了。

2.web.xml配置,因为是最简单springmvc,所以web.xml只是用来加载下上下文,web.xml配置文件路径:src\main\webapp\WEB-INF:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" metadata-complete="false" version="3.1">
	<description>TestMock</description>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener> 

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml,classpath*:dubbo-provider.xml</param-value>
    </context-param>
</web-app>

3.mybatis配置文件和代码可以用MyBatis Generator自动生成即可,mybatis的相关代码和配置如下:

    3.1 数据库为mysql,表名books,表结构如下:

    

    3.2 mapping文件BookMapper.xml路径为resources下的com\ly\mapping,如下:

<?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.ly.dao.BookDAO">
    <!--id应该是接口中的方法,结果类型如没有配置别名则应该使用全名称 -->
    <!--获得所有图书 -->
    <select id="getAllBooks" resultType="com.ly.model.Book">
        select id,title,price,publistDate from books
    </select>
    <!--获得图书对象通过编号 -->
    <select id="getBookById" resultType="com.ly.model.Book">
        select id,title,price,publistDate from books where id=#{id}
    </select>
    <!-- 增加 -->
    <insert id="add">
        insert into books(title,price,publistDate)
        values(#{title},#{price},#{publistDate})
    </insert>
    <!-- 删除 -->
    <delete id="delete">
        delete from books where id=#{id}
    </delete>
    <!-- 更新 -->
    <update id="update">
        update books set title=#{title},price=#{price},publistDate=#{publistDate}
        where id=#{id}
    </update>
</mapper>

3.3 DAO代码 BookDAO.java如下:

package com.ly.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.ly.model.Book;


public interface BookDAO {
	
	/**
	 * 获取所有图书
	 * @return
	 */
	public List<Book> getAllBooks();
	
	/**
	 * 根据id获取图书
	 * @param id
	 * @return
	 */
	public Book getBookById(@Param("id")int id);
	
	/**
	 * 添加图书
	 * @param entity
	 * @return
	 */
	public int add(Book entity);
	
	/**
	 * 根据id删除图书
	 * @param id
	 * @return
	 */
	public int delete(int id);
	
	/**
	 * 更新图书
	 * @param entity
	 * @return
	 */
	public int update(Book entity);
}

    3.4 model代码 Book.java如下:

package com.ly.model;

import java.util.Date;

public class Book {
	
	private int id;
	
	private String title;
	
	private double price;
	
	private Date publistDate;
	
	public Book(){}
	
	public Book(int id, String title, double price, Date publistDate) {
		this.id = id;
		this.title = title;
		this.price = price;
		this.publistDate = publistDate;
	}
	
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public Date getPublistDate() {
		return publistDate;
	}

	public void setPublistDate(Date publistDate) {
		this.publistDate = publistDate;
	}

}

 3.5 BookServer.java代码如下:

package com.ly.server;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ly.dao.BookDAO;
import com.ly.model.Book;

@Service
public class BookServer {
	@Autowired
	private BookDAO bookDAO;
	
	public List<Book> getAllBooks() {
		return bookDAO.getAllBooks();
	}
	
	public Book getBookById(int id) {
		return bookDAO.getBookById(id);
	}
}


4. spring配置文件applicationContext.xml 位于 resources下,如下:

<?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:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    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-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!--1 引入属性文件,在配置中占位使用 -->
    <context:property-placeholder location="classpath*:stock.properties" />

	<!-- 数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<property name="url" value="${mock.jdbc.url}" />
		<property name="driverClassName" value="${mock.jdbc.driver}" />
		<property name="username" value="${mock.jdbc.username}" />
		<property name="password" value="${mock.jdbc.password}" />
		<property name="initialSize" value="${mock.jdbc.initialSize}" />
		<property name="minIdle" value="${mock.jdbc.minIdle}" />
		<property name="maxWait" value="${mock.jdbc.maxWait}" />
		<property name="maxActive" value="${mock.jdbc.maxActive}" />
	</bean>
	    
    <!--3 会话工厂bean sqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- sql映射文件路径 -->
        <property name="mapperLocations" value="classpath:com/ly/mapping/*Mapper.xml"></property>
    </bean>
    
    <!--4 自动扫描对象关系映射 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去,多个数据库启用 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <!-- 指定要自动扫描接口的基础包,实现接口 -->
        <property name="basePackage" value="com.ly.dao"></property>
    </bean>
    
    <!--5 声明式事务管理 -->
    <!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--支持注解驱动的事务管理,指定事务管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--6 容器自动扫描IOC组件  -->
    <context:component-scan base-package="com.ly"></context:component-scan>
    
    <!--7 aspectj支持自动代理实现AOP功能 -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>

其中stock.properties中的数据源配置为你自己的mysql数据库,我的如下:

mock.jdbc.url = jdbc:mysql://127.0.0.1:5508/mock?useUnicode=true&characterEncoding=UTF-8

mock.jdbc.driver = com.mysql.jdbc.Driver

mock.jdbc.username = mock

mock.jdbc.password = mock

mock.jdbc.initialSize = 1

mock.jdbc.minIdle = 2

mock.jdbc.maxWait = 5000

mock.jdbc.maxActive = 5


具体的applicationContext.xml含义基本有注释


5. dubbo的配置和代码

    5.1 dubbo配置文件 dubbo-provider.xml 也位于 resources下,zookeeper自己本地安装一个,如下:

<?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="TestMockServer" />  
  
    <!-- 注册地址 -->  
    <dubbo:registry address="zookeeper://127.0.0.1:2181" />  
  
    <!-- 接口的位置 -->  
    <dubbo:service interface="com.ly.server.SayHelloServer"  
                   ref="frameService" executes="10" />  
  
  
    <!-- 实现bean,客户端应用的bean就以这个id名称为主 -->  
    <bean id="frameService" class="com.ly.server.impl.SayHelloServerImpl" />  
  
</beans>  

  5.2 dubbo接口代码 SayHelloServer.java如下:    

package com.ly.server;

public interface SayHelloServer {
	public String sayHello(String hello);
}

 5.2 接口实现代码SayHelloServerImpl.java 如下:

package com.ly.server.impl;

import com.ly.server.SayHelloServer;

public class SayHelloServerImpl implements SayHelloServer {

	public String sayHello(String hello) {
		System.out.println("Client: "+ hello);
		return hello + "   Server: ";
	}
}

现在基本上SpringMvc+Spring+Mybatis+Mysql+Dubbo就已经整合完成了,本地下载一个tomcat,把项目打包发布到tomcat下启动,就能在dubbo的monitor中发现该项目的SayHelloServer接口已经注册在zk上面了。


附上我的自动发布shell脚本,一个很简单的shell脚本:

#!/bin/sh

#判断进程存在
tomcatId=0
tomcatID=`ps -ef | grep org.apache.catalina.startup.Bootstrap | grep -v grep | awk '{print $2}'`
echo "MockServer tomcat is " $tomcatID

if [ -n "$tomcatID" ];then
	echo 'current tomcat pid is:'$tomcatID
	kill -15 $tomcatID && echo  "MockServer kill -15"
	kill -9 $tomcatID && echo "MockServer kill -9"
else
	echo $sysName " not start"
fi
sleep 2

#编译
cd /Users/ly/Documents/workspace/MockServer
mvn clean install -Dmaven.test.skip=true -U
sleep 5

#部署本地
cd target
rm -rf /Users/ly/tomcat/apache-tomcat-9.0.4/webapps/ROOT/*
unzip -q mock_server.war -d /Users/ly/tomcat/apache-tomcat-9.0.4/webapps/ROOT/

nohup sh /Users/ly/tomcat/apache-tomcat-9.0.4/bin/startup.sh & sleep 3
echo "MockServer is starting......"





posted @ 2018-02-27 15:20  luoylove  阅读(498)  评论(0编辑  收藏  举报