springboot+mybatis+dubbo整合

PS:搭建框架过程在网上查询了比较多的资料,最后自己再综合得到,如有侵权,请联系删除!

 最近整合了springboot+mybatis+dubbo的架构,分享给大家!首先Demo目录架构如下:


首先项目外层定义版本等的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.sb</groupId>
  <artifactId>springBootDemo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>springBootDemo1</name>
  <description>springBootDemo1</description>
    
  <properties>
  	<jdk.version>1.7</jdk.version>
  	<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
  	<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
  	<org.mybatis.generator.version>1.3.2</org.mybatis.generator.version>
	<mybatis.version>3.1.1</mybatis.version>
	<mybatis-spring.version>1.2.0</mybatis-spring.version>
	<dubbo.version>2.4.9</dubbo.version>
	<zookeeper.version>3.4.5</zookeeper.version>
	<zkclient.version>0.1</zkclient.version>
	<com.alibaba.druid.version>0.2.6</com.alibaba.druid.version>
  </properties>
  <!-- springboot使用1.4.1.RELEASE版本 -->
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>
  
  <build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
					<encoding>UTF-8</encoding>
				</configuration>

			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
  <modules>
  	<module>springboot-comm</module>
  	<module>springboot-app</module>
  	<module>springboot-web1</module>
  </modules>
</project>
springboot-app下面的Application.java,主要用注解方式加载Bean,而且服务提供者的启动main方法也写在这下面,代码如下:

package com.springboot.application;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;


@MapperScan("com.springboot.mapper")
@SpringBootApplication
@ImportResource(locations={"dubbo-provider.xml"})
public class Application {
	
<span style="white-space:pre">	</span>private static volatile boolean running = true;
	
    private static Logger logger = Logger.getLogger(Application.class);
 
    //DataSource配置
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource() {
        return new com.alibaba.druid.pool.DruidDataSource();
    }
 
    //提供SqlSeesion
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis-mapping/*.xml"));
 
        return sqlSessionFactoryBean.getObject();
    }
 
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
    
    /**
     * Main 方法启动项
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("============= APP Start ON SpringBoot Success =============");
        synchronized (Application.class) {
			while (running) {
				try {
					Application.class.wait();
				} catch (Throwable e) {
				}
			}
		}
    }
  
}
启动app层的main方法之后,会自动加载bean,  @ConfigurationProperties(prefix="spring.datasource")会自动去application.properties下面以spring.datasource开头的有关数据库连接的配置文件,application.properties如下:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


dubbo.registry.center=127.0.0.1:2181
dubbo.protocol.port=20885


通过注解@MapperScan("com.springboot.mapper")自动扫描mybatis的mapper文件,mapper代码如下:

package com.springboot.mapper;

import com.springboot.domain.User;

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

UserMapper.xml,使用mybatis逆向工程生产的,没改动,代码如下:

<?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.springboot.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.springboot.domain.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="password" property="password" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, name, age, password
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.springboot.domain.User" >
    insert into user (id, name, age, 
      password)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{password,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.springboot.domain.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="password != null" >
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.springboot.domain.User" >
    update user
    <set >
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.springboot.domain.User" >
    update user
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

springboot-comm:主要放实体、接口、也可以放一些公用的工具类,实体如下:
private Integer id;

    private String name;

    private Integer age;

    private String password;

接口如下:

package com.springboot.service;

import com.springboot.domain.User;

public interface UserService {

	User getById(Integer id);

}
接下来是接口的实现,放在app层,都比较简单,如下:
package com.springboot.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.springboot.domain.User;
import com.springboot.mapper.UserMapper;
import com.springboot.service.UserService;

@Service("userService")
public class userServiceImpl implements UserService {
	
	@Resource
	private UserMapper userMapper;
	
	
	/* (non-Javadoc)
	 * @see com.spring.service.impl.user.userService#getById(java.lang.Integer)
	 */
	@Override
	public User getById(Integer id){
		return userMapper.selectByPrimaryKey(id);
	}
}

服务提供者的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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
		http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    <context:component-scan base-package="com.springboot.service.*">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<dubbo:application name="springBoot-service-provider-app" />
    <!-- Dubbo注册地址 -->
	<dubbo:registry protocol="zookeeper" address="${dubbo.registry.center}" />
	<dubbo:protocol name="dubbo" port="${dubbo.protocol.port}" threadpool="cached" threads="1000" accepts="2000" serialization="java"/>
	 
 	<dubbo:service interface="com.springboot.service.UserService" ref="userService" timeout="3000" ></dubbo:service>
</beans>

自己本地可以下载一个单机版的zookeeper

app的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>
  <parent>
    <groupId>com.sb</groupId>
    <artifactId>springBootDemo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>springboot-app</artifactId>
  <dependencies>
  	<dependency>
  		<groupId>com.sb</groupId>
  		<artifactId>springboot-comm</artifactId>
  		<version>0.0.1-SNAPSHOT</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
  	</dependency>
  	  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
       </dependency>
      <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.sgroschupf</groupId>
			<artifactId>zkclient</artifactId>
			<version>${zkclient.version}</version>
			<exclusions>
				<exclusion>
					<groupId>log4j</groupId>
					<artifactId>log4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
         <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>${org.mybatis.generator.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>${dubbo.version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>${zookeeper.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>jmxtools</artifactId>
					<groupId>com.sun.jdmk</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jmxri</artifactId>
					<groupId>com.sun.jmx</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jms</artifactId>
					<groupId>javax.jms</groupId>
				</exclusion>
				<exclusion>
					<groupId>log4j</groupId>
					<artifactId>log4j</artifactId>
				</exclusion>
				<exclusion>
					<artifactId>slf4j-log4j12</artifactId>
					<groupId>org.slf4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${com.alibaba.druid.version}</version>
		</dependency>
  </dependencies>
  
  <build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
					<encoding>UTF-8</encoding>
				</configuration>

			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

到了这里,我们的服务已经可以完成了,运行application.java的main方法,我们可以看到控制台如下,就代表成功了!是不是比以前少了很多配置文件,2333!!



然后我们到web层,到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>
  <parent>
    <groupId>com.sb</groupId>
    <artifactId>springBootDemo1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>springboot-web1</artifactId>
  <packaging>war</packaging>
  
   <dependencies>
  	<dependency>
  		<groupId>com.sb</groupId>
  		<artifactId>springboot-comm</artifactId>
  		<version>0.0.1-SNAPSHOT</version>
  	</dependency>
  	<dependency>
  		 <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
  	</dependency>
  	<!-- add for dubbo start -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>${dubbo.version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>${zookeeper.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>jmxtools</artifactId>
					<groupId>com.sun.jdmk</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jmxri</artifactId>
					<groupId>com.sun.jmx</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jms</artifactId>
					<groupId>javax.jms</groupId>
				</exclusion>
				<exclusion>
					<groupId>org.slf4j</groupId>
					<artifactId>slf4j-log4j12</artifactId>
				</exclusion>
				<exclusion>
					<groupId>log4j</groupId>
					<artifactId>log4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.github.sgroschupf</groupId>
			<artifactId>zkclient</artifactId>
			<version>${zkclient.version}</version>
			<exclusions>
				<exclusion>
					<groupId>log4j</groupId>
					<artifactId>log4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
  </dependencies>
  <build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
					<encoding>UTF-8</encoding>
				</configuration>

			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

application.properties如下:
dubbo.registry.center=127.0.0.1:2181
springboot会自动加载配置文件,你有什么自定义的属性也可以写在这里,${名称},配置文件就可以取到,非常方便


然后服务消费者代码如下:

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
		http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

	<context:annotation-config />
	<dubbo:application name="springboot-service-consumer-app" />
	<dubbo:registry id="springboot-reg" protocol="zookeeper" address="${dubbo.registry.center}" />
	<dubbo:annotation />
    
	<context:component-scan base-package="com.springboot.*">
		<context:include-filter type="annotation"
			expression="com.alibaba.dubbo.config.annotation.Reference" />
	</context:component-scan>

	<!-- <dubbo:reference  interface="com.springboot.service.UserService" id="userService"/> -->
	
</beans>

demoController的代码如下:

package com.springboot.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.springboot.domain.User;
import com.springboot.service.UserService;

@RestController
@RequestMapping("/user")
public class demoController {
 
    private static Logger logger = Logger.getLogger(demoController.class);
 
    @Reference
    private UserService userService;
 
    /*
     *  http://localhost:8080/user/getUserById?id=1
     */
 
    @RequestMapping("/getUserById")
    public Object getUserById(@RequestParam("id")Integer id) {
        User user = userService.getById(id);
        if(user!=null){
            System.out.println("user.getName():"+user.getName());
            logger.info("user.getAge():"+user.getAge());
        }
        return user;
    }
    
}


最后就是到web的启动项,你只需要运行这个main方法,项目就可以访问了,webStartApp.java代码如下:

package com.springboot.application;

import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;


@SpringBootApplication(scanBasePackages="com.springboot.controller")
@ImportResource(locations = {"dubbo-consumer.xml"})
public class webStartApp {
	
	 private static Logger logger = Logger.getLogger(webStartApp.class);
	 /**
     * Main Start
     */
    public static void main(String[] args) {
        SpringApplication.run(webStartApp.class, args);
        System.out.println("============= SpringBoot web Start Success =============");
    }
}

@SpringBootApplication(scanBasePackages="com.springboot.controller") 括号里面的内容,如果Controller和启动main同一个包下面是不需要指向的,如果要放在不同包下面不加scanBasePackages="com.springboot.controller"会报错!


然后我们现在启动webStartApp ,如果成功,我们会看到控制台如下:




我的数据库里面存了两条数据:


这时候我们就可以访问试一下,看到返还的如下JSON数据,就证明我们项目跑起来了:

控制台也会有对应的输出:


到这里,我们的整合已经完成了,希望对你有帮助!!

PS:第一次写博客,写得不好请多多包涵。

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值