快速上手(三)服務(wù)提供者 - 項目搭建

項目結(jié)構(gòu)

項目是以Maven構(gòu)建的多模塊項目垂睬,1個父項目媳荒,3個子項目抗悍;

Parent Model - dubboOne

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.debug.mooc.dubbo.one</groupId>
    <artifactId>dubboOne</artifactId>
    <packaging>pom</packaging>
    <version>1.0.1</version>
    <modules>
        <module>api</module>
        <module>model</module>
        <module>server</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>

</project>

Sub Model - api

pom.xml
  • 有自己的 <artifactId>api</artifactId>;
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <groupId>com.debug.mooc.dubbo.one</groupId>
        <artifactId>dubboOne</artifactId>
        <version>1.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>api</artifactId>
    
    <properties>
        <mybatis-pagehelper.version>4.1.2</mybatis-pagehelper.version>
        <lombok.version>1.16.10</lombok.version>
    </properties>

    <dependencies>
        <!--java校驗 跟 hibernate校驗-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.5.Final</version>
        </dependency>

        <!--for page-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${mybatis-pagehelper.version}</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>

    </dependencies>

</project>
向注冊中心提供的接口
package com.debug.mooc.dubbo.one.api.service;

import com.debug.mooc.dubbo.one.api.response.BaseResponse;

public interface IDubboItemService {

    BaseResponse listItems();

    BaseResponse listPageItems(Integer pageNo,Integer pageSize);

    BaseResponse listPageItemsParams(Integer pageNo,Integer pageSize,String search);

}

Sub Model - model

pom.xml
  • 有自己的 <artifactId>model</artifactId>钳枕;
  • 依賴于 api 子模塊缴渊;
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>dubboOne</artifactId>
        <groupId>com.debug.mooc.dubbo.one</groupId>
        <version>1.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>model</artifactId>
    <properties>
        <mybatis-spring-boot.version>1.1.1</mybatis-spring-boot.version>
        <mybatis-pagehelper.version>4.1.2</mybatis-pagehelper.version>
    </properties>

    <dependencies>
        <!--api-->
        <dependency>
            <groupId>com.debug.mooc.dubbo.one</groupId>
            <artifactId>api</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <!--spring-mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot.version}</version>
        </dependency>

    </dependencies>

</project>
實(shí)現(xiàn)用于和數(shù)據(jù)庫交互的 dao 層
  • Entity
package com.debug.mooc.dubbo.one.model.entity;

import lombok.ToString;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

@ToString
public class ItemInfo implements Serializable{
    private Integer id;

    private String code;

    private String name;

    private BigDecimal price;

    private Integer isActive;

    private Date createTime;

    private Date updateTime;

    public Integer getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public BigDecimal getPrice() {
        return price;
    }

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

    public Integer getIsActive() {
        return isActive;
    }

    public void setIsActive(Integer isActive) {
        this.isActive = isActive;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}
dao 層接口
package com.debug.mooc.dubbo.one.model.mapper;

import com.debug.mooc.dubbo.one.model.entity.ItemInfo;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface ItemInfoMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(ItemInfo record);

    int insertSelective(ItemInfo record);

    ItemInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(ItemInfo record);

    int updateByPrimaryKey(ItemInfo record);

    List<ItemInfo> selectAll();

    List<ItemInfo> selectAllByParams(@Param("search") String search);
}

dao 層 SQL

<?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.debug.mooc.dubbo.one.model.mapper.ItemInfoMapper" >
  <resultMap id="BaseResultMap" type="com.debug.mooc.dubbo.one.model.entity.ItemInfo" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="code" property="code" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="price" property="price" jdbcType="DECIMAL" />
    <result column="is_active" property="isActive" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, code, name, price, is_active, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from item_info
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from item_info
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.debug.mooc.dubbo.one.model.entity.ItemInfo" >
    insert into item_info (id, code, name, 
      price, is_active, create_time, 
      update_time)
    values (#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 
      #{price,jdbcType=DECIMAL}, #{isActive,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, 
      #{updateTime,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.debug.mooc.dubbo.one.model.entity.ItemInfo" >
    insert into item_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="code != null" >
        code,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="price != null" >
        price,
      </if>
      <if test="isActive != null" >
        is_active,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="updateTime != null" >
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="code != null" >
        #{code,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=DECIMAL},
      </if>
      <if test="isActive != null" >
        #{isActive,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.debug.mooc.dubbo.one.model.entity.ItemInfo" >
    update item_info
    <set >
      <if test="code != null" >
        code = #{code,jdbcType=VARCHAR},
      </if>
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=DECIMAL},
      </if>
      <if test="isActive != null" >
        is_active = #{isActive,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.debug.mooc.dubbo.one.model.entity.ItemInfo" >
    update item_info
    set code = #{code,jdbcType=VARCHAR},
      name = #{name,jdbcType=VARCHAR},
      price = #{price,jdbcType=DECIMAL},
      is_active = #{isActive,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>

  <!--查詢列表-->
  <select id="selectAll" resultType="com.debug.mooc.dubbo.one.model.entity.ItemInfo">
    SELECT <include refid="Base_Column_List"/>
    FROM item_info
    WHERE is_active = 1
    ORDER BY create_time DESC
  </select>

  <!--列表查詢-模糊查詢-->
  <select id="selectAllByParams" resultType="com.debug.mooc.dubbo.one.model.entity.ItemInfo">
    SELECT *
    FROM item_info
    WHERE is_active = 1
      <if test="search!=null and search!='' ">
        AND name LIKE CONCAT('%', '${search}', '%')
      </if>
    ORDER BY create_time DESC
  </select>

</mapper>

Sub Model - server

  • 作為服務(wù)提供者的主體,是個 Springboot 項目鱼炒,統(tǒng)籌其他子模塊衔沼;
  • 實(shí)現(xiàn) api 子模塊中向注冊中心暴露的接口;
  • 整合 Dubbo & Zookeeper & MySQL & Log昔瞧;
pom.xml
  • 有自己的 <artifactId>server</artifactId>指蚁;
  • 依賴于 model 子模塊;
  • 注意 spring-boot-starter-web 中要 exclusion 兩個 log 實(shí)現(xiàn)自晰;
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>dubboOne</artifactId>
        <groupId>com.debug.mooc.dubbo.one</groupId>
        <version>1.0.1</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>server</artifactId>
    <packaging>jar</packaging>

    <properties>
        <start-class>com.debug.mooc.dubbo.one.server.BootMoreApplication</start-class>

        <!--<spring-boot.version>1.3.3.RELEASE</spring-boot.version>-->
        <spring-boot.version>2.0.5.RELEASE</spring-boot.version>

        <spring-session.version>1.2.0.RELEASE</spring-session.version>
        <slf4j.version>1.7.13</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <mysql.version>5.1.37</mysql.version>
        <druid.version>1.0.16</druid.version>
        <guava.version>19.0</guava.version>
        <joda-time.version>2.9.2</joda-time.version>
        <cglib.version>3.1</cglib.version>

        <zookeeper.version>3.4.10</zookeeper.version>
        <curator.version>2.12.0</curator.version>
        <dubbo.version>2.8.4</dubbo.version>

        <resteasy.version>3.0.7.Final</resteasy.version>
        <okhttp.version>3.1.2</okhttp.version>
        <gson.version>2.6.1</gson.version>
        <httpclient.version>4.3.6</httpclient.version>

    </properties>

    <!-- 依賴管理 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <!--model-->
        <dependency>
            <groupId>com.debug.mooc.dubbo.one</groupId>
            <artifactId>model</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <!--log-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!--<dependency>-->
            <!--<groupId>org.slf4j</groupId>-->
            <!--<artifactId>slf4j-log4j12</artifactId>-->
            <!--<version>${slf4j.version}</version>-->
        <!--</dependency>-->

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <!--guava-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>

        <!-- time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${joda-time.version}</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>ch.qos.logback</groupId>
                    <artifactId>logback-classic</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- jsp 支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- dubbo -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>${dubbo.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>curator-framework</artifactId>
                    <groupId>org.apache.curator</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>curator-client</artifactId>
                    <groupId>org.apache.curator</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>spring-web</artifactId>
                    <groupId>org.springframework</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>${cglib.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>asm</artifactId>
                    <groupId>org.ow2.asm</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- zookeeper start -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>${zookeeper.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>${curator.version}</version>
        </dependency>

        <!--dubbo rest-->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>${resteasy.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>httpclient</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-netty</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>


        <!--for test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>${gson.version}</version>
        </dependency>

        <!-- okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>${okhttp.version}</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>dubboOne-${project.parent.version}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>


</project>
application.properties
  • tomcat 監(jiān)聽在 8093 端口凝化;
  • 整合 mybatis 部分會指向 model 子模塊中的classpath;
  • 指定了注冊中心 zookeeper 的地址酬荞;
#profile
#spring.profiles.active=production
#spring.profiles.active=local

server.port=8093
#server.context-path=/dubboOne
server.servlet.context-path=/dubboOne

#logging

logging.path=/
logging.file=dubboOne.log


logging.level.org.springframework = INFO
logging.level.com.fasterxml.jackson = INFO
logging.level.com.debug.mooc.dubbo.one = debug

#json\u5E8F\u5217\u5316\u914D\u7F6E
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

#spring.datasource.initialize=false
spring.datasource.initialization-mode=never
spring.jmx.enabled=false

#\u6570\u636E\u6E90\u914D\u7F6E
datasource.url=jdbc:mysql://127.0.0.1:3306/mooc_one?useUnicode=true&amp;characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
datasource.username=root
datasource.password=MyNewPass4!

#mybatis
mybatis.config-location=classpath:mybatis-config.xml
mybatis.checkConfigLocation = true
mybatis.mapper-locations=classpath:mappers/*.xml


#dubbo zookeeper\u914D\u7F6E\u4FE1\u606F
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo 配置(一) - spring/spring-dubbo.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">

    <!--發(fā)布出去的接口在哪個包下實(shí)現(xiàn)-->
    <dubbo:annotation package="com.debug.mooc.dubbo.one.server.service.dubbo" />

    <!--注冊中心zookeeper配置信息-->
    <dubbo:registry address="${dubbo.registry.address}" />

    <!--支持兩種協(xié)議的調(diào)用:rpc-dubbo協(xié)議搓劫;http協(xié)議-rest api-url調(diào)用-->
    <dubbo:protocol name="rest" threads="500" contextpath="v1" server="tomcat" accepts="500"/>
    <dubbo:protocol name="dubbo" />

    <!--消費(fèi)方信息配置-->
    <dubbo:application name="dubboOne-consume" owner="debug" organization="dubbox"/>


</beans>
dubbo 配置(二) - dubbo.properties
  • RPC 在 20903 端口監(jiān)聽;
  • HTTP 在 9013 端口監(jiān)聽袜蚕;
dubbo.container=log4j,spring
dubbo.reference.check=false
dubbo.registry.client=curator
dubbo.application.name=dubboOne-provider
dubbo.application.owner=debug

#dubbo
dubbo.protocol.name=dubbo
dubbo.protocol.dubbo.port=20903

#dubbo
dubbo.protocol.name=rest
dubbo.protocol.rest.port=9013
dubbo.protocol.rest.server=tomcat

dubbo.service.loadbalance=roundrobin
數(shù)據(jù)庫連接池 - spring/spring-jdbc.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       " >

    <!--dubboOne -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close" primary="true" >
        <!-- 基本屬性 url糟把、user、password -->
        <property name="url" value="${datasource.url}" />
        <property name="username" value="${datasource.username}" />
        <property name="password" value="${datasource.password}" />

        <!-- 配置初始化大小牲剃、最小遣疯、最大 -->
        <property name="initialSize" value="10" />
        <property name="minIdle" value="10" />
        <property name="maxActive" value="20" />

        <!-- 配置獲取連接等待超時的時間 -->
        <property name="maxWait" value="60000" />

        <!-- 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接凿傅,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一個連接在池中最小生存的時間缠犀,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 1 " />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打開PSCache,并且指定每個連接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置監(jiān)控統(tǒng)計攔截的filters聪舒,去掉后監(jiān)控界面sql無法統(tǒng)計 -->
        <property name="filters" value="stat" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>
mybatis 相關(guān)配置
  • 主要是分頁插件的配置辨液;
<?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>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 設(shè)置控制臺打印sql -->
        <!--<setting name="logImpl" value="stdout_logging" />-->
    </settings>

    <!-- Continue going here -->

    <!--<typeAliases>-->
        <!--<package name="cn.com.countrygarden.ucenter.entity"/>-->
    <!--</typeAliases>-->
    <plugins>
        <!-- com.github.pagehelper為PageHelper類所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 4.0.0以后版本可以不設(shè)置該參數(shù) -->
            <property name="dialect" value="mysql"/>
            <!-- 該參數(shù)默認(rèn)為false -->
            <!-- 設(shè)置為true時,會將RowBounds第一個參數(shù)offset當(dāng)成pageNum頁碼使用 -->
            <!-- 和startPage中的pageNum效果一樣-->
            <property name="offsetAsPageNum" value="true"/>
            <!-- 該參數(shù)默認(rèn)為false -->
            <!-- 設(shè)置為true時箱残,使用RowBounds分頁會進(jìn)行count查詢 -->
            <property name="rowBoundsWithCount" value="true"/>
            <!-- 設(shè)置為true時滔迈,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結(jié)果 -->
            <!-- (相當(dāng)于沒有執(zhí)行分頁查詢,但是返回結(jié)果仍然是Page類型)-->
            <property name="pageSizeZero" value="true"/>
            <!-- 3.3.0版本可用 - 分頁參數(shù)合理化被辑,默認(rèn)false禁用 -->
            <!-- 啟用合理化時燎悍,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最后一頁 -->
            <!-- 禁用合理化時盼理,如果pageNum<1或pageNum>pages會返回空數(shù)據(jù) -->
            <property name="reasonable" value="false"/>
            <!-- 3.5.0版本可用 - 為了支持startPage(Object params)方法 -->
            <!-- 增加了一個`params`參數(shù)來配置參數(shù)映射谈山,用于從Map或ServletRequest中取值 -->
            <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默認(rèn)值 -->
            <!-- 不理解該含義的前提下,不要隨便復(fù)制該配置 -->
            <!--<property name="params" value="pageNum=pageHelperStart;pageSize=pageHelperRows;"/>-->
            <!-- 支持通過Mapper接口參數(shù)來傳遞分頁參數(shù) -->
            <property name="supportMethodsArguments" value="false"/>
            <!-- always總是返回PageInfo類型,check檢查返回類型是否為PageInfo,none返回Page -->
            <property name="returnPageInfo" value="none"/>
        </plugin>
    </plugins>

    <!--<mappers>-->
        <!--&lt;!&ndash;<package name="cn.com.countrygarden.ucenter.mapper" />&ndash;&gt;-->
        <!--<mapper resource="mappers/DiaryMapper.xml"/>-->
        <!--<mapper resource="mappers/EmpEvaluateMapper.xml"/>-->
        <!--<mapper resource="mappers/EmployeeMapper.xml"/>-->
        <!--<mapper resource="mappers/LikesMapper.xml"/>-->
        <!--<mapper resource="mappers/PicMapper.xml"/>-->
        <!--<mapper resource="mappers/RepliesMapper.xml"/>-->
        <!--<mapper resource="mappers/TeamMapper.xml"/>-->
        <!--<mapper resource="mappers/UserMapper.xml"/>-->
    <!--</mappers>-->
</configuration>
日志相關(guān)配置
#Console Log
log4j.rootLogger=INFO,console,debug,info,warn,error

LOG_PATTERN=[%d{yyyy-MM-dd HH:mm:ss.SSS}] boot%X{context} - %5p [%t] --- %c{1}: %m%n
LOG_PATH=C:\Users\LiXinlei\Desktop
LOG_FILE=dubbo

#A1--Print log to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.Threshold=INFO
log4j.appender.info.File=${LOG_PATH}/${LOG_FILE}_info.log
log4j.appender.info.DatePattern='.'yyyy-MM-dd
log4j.appender.info.layout = org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.Threshold=ERROR
log4j.appender.error.File=${LOG_PATH}/${LOG_FILE}_error.log
log4j.appender.error.DatePattern='.'yyyy-MM-dd
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=${LOG_PATTERN}


log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.File=${LOG_PATH}/${LOG_FILE}_debug.log
log4j.appender.debug.DatePattern='.'yyyy-MM-dd
log4j.appender.debug.layout = org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=${LOG_PATTERN}

log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.File=${LOG_PATH}/${LOG_FILE}_warn.log
log4j.appender.warn.DatePattern='.'yyyy-MM-dd
log4j.appender.warn.layout = org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=${LOG_PATTERN}
啟動類
  • 加載數(shù)據(jù)源配置文件宏怔;
  • 加載 dubbo 配置文件奏路;
  • 加載 sql 文件畴椰;
package com.debug.mooc.dubbo.one.server;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
//import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(value = {"classpath:spring/spring-jdbc.xml","classpath:spring/spring-dubbo.xml"})
@MapperScan(basePackages = "com.debug.mooc.dubbo.one.model.mapper")
public class BootMoreApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(BootMoreApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(BootMoreApplication.class, args);
    }

}
api 模塊開放給注冊中心的接口的實(shí)現(xiàn)
package com.debug.mooc.dubbo.one.server.service.dubbo;/**
 * Created by Administrator on 2019/1/13.
 */

import com.alibaba.dubbo.config.annotation.Service;
import com.debug.mooc.dubbo.one.api.enums.StatusCode;
import com.debug.mooc.dubbo.one.api.response.BaseResponse;
import com.debug.mooc.dubbo.one.api.service.IDubboItemService;
import com.debug.mooc.dubbo.one.model.entity.ItemInfo;
import com.debug.mooc.dubbo.one.model.mapper.ItemInfoMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.List;

/**
 * @Author:debug (SteadyJack)
 * @Date: 2019/1/13 14:21
 **/
@Service(protocol = {"dubbo","rest"},validation = "true",version = "1.0",timeout = 3000)
@Path("moocOne")
public class DubboItemService implements IDubboItemService{

    private static final Logger log= LoggerFactory.getLogger(DubboItemService.class);

    @Autowired
    private ItemInfoMapper itemInfoMapper;

    /**
     * 列表查詢服務(wù)-實(shí)際的業(yè)務(wù)實(shí)現(xiàn)邏輯
     * @return
     */
    @Path("item/list")
    public BaseResponse listItems() {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            List<ItemInfo> infos = itemInfoMapper.selectAll();
            log.info("查詢到的商品列表數(shù)據(jù):{} ", infos);
            response.setData(infos);
        }catch (Exception e){
            log.error("列表查詢服務(wù)-實(shí)際的業(yè)務(wù)實(shí)現(xiàn)邏輯-發(fā)生異常:", e.fillInStackTrace());
            response = new BaseResponse(StatusCode.Fail);
        }
        return response;
    }




    /**
     * 列表查詢-分頁查詢
     * @return
     */
    @Path("item/page/list")
    public BaseResponse listPageItems(@QueryParam("pageNo") Integer pageNo,
                                      @QueryParam("PageSize") Integer PageSize) {
        BaseResponse response = new BaseResponse(StatusCode.Success);
        try {
            //TODO:分頁組件-第pageNo頁,pageSize條數(shù)目數(shù)據(jù)
            PageHelper.startPage(pageNo, PageSize);
            PageInfo info = new PageInfo<ItemInfo>(itemInfoMapper.selectAll());
            response.setData(info);
        }catch (Exception e){
            log.error("列表查詢-分頁查詢服務(wù)-實(shí)際的業(yè)務(wù)實(shí)現(xiàn)邏輯-發(fā)生異常:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail);
        }
        return response;
    }

    /**
     * 列表查詢-分頁查詢-模糊查詢
     * @return
     */
    @Path("item/page/list/params")
    public BaseResponse listPageItemsParams(@QueryParam("pageNo") Integer pageNo,
                                      @QueryParam("PageSize") Integer PageSize,
                                      @QueryParam("search") String search) {
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            //TODO:分頁組件-第pageNo頁鸽粉,pageSize條數(shù)目數(shù)據(jù)
            PageHelper.startPage(pageNo,PageSize);
            PageInfo info=new PageInfo<ItemInfo>(itemInfoMapper.selectAllByParams(search));
            response.setData(info);

        }catch (Exception e){
            log.error("列表查詢-分頁查詢模糊查詢服務(wù)-實(shí)際的業(yè)務(wù)實(shí)現(xiàn)邏輯-發(fā)生異常:",e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail);
        }
        return response;
    }
}

發(fā)布項目

  • 啟動 Springboot 項目斜脂;
  • 在父模塊的根目錄下:mvn clean install -Dmaven.test.skip=true;

上一篇:快速上手(二)在 Windows 快速啟動 Zookeeper
下一篇:快速上手(四)服務(wù)消費(fèi)者 - 項目搭建

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末潜叛,一起剝皮案震驚了整個濱河市秽褒,隨后出現(xiàn)的幾起案子壶硅,更是在濱河造成了極大的恐慌威兜,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庐椒,死亡現(xiàn)場離奇詭異椒舵,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)约谈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進(jìn)店門笔宿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人棱诱,你說我怎么就攤上這事泼橘。” “怎么了迈勋?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵炬灭,是天一觀的道長。 經(jīng)常有香客問我靡菇,道長重归,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任厦凤,我火速辦了婚禮鼻吮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘较鼓。我一直安慰自己椎木,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布博烂。 她就那樣靜靜地躺著香椎,像睡著了一般。 火紅的嫁衣襯著肌膚如雪脖母。 梳的紋絲不亂的頭發(fā)上士鸥,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機(jī)與錄音谆级,去河邊找鬼烤礁。 笑死讼积,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的脚仔。 我是一名探鬼主播勤众,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼鲤脏!你這毒婦竟也來了们颜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤猎醇,失蹤者是張志新(化名)和其女友劉穎窥突,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體硫嘶,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡阻问,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了沦疾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片称近。...
    茶點(diǎn)故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖哮塞,靈堂內(nèi)的尸體忽然破棺而出刨秆,到底是詐尸還是另有隱情,我是刑警寧澤忆畅,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布衡未,位于F島的核電站,受9級特大地震影響邻眷,放射性物質(zhì)發(fā)生泄漏眠屎。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一肆饶、第九天 我趴在偏房一處隱蔽的房頂上張望改衩。 院中可真熱鬧,春花似錦驯镊、人聲如沸葫督。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽橄镜。三九已至,卻和暖如春冯乘,著一層夾襖步出監(jiān)牢的瞬間洽胶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工裆馒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留姊氓,地道東北人丐怯。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像翔横,于是被迫代替她去往敵國和親读跷。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內(nèi)容