程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> dubbo+zookeeper+spring+springMVC+mybatis的使用,dubbozookeeper

dubbo+zookeeper+spring+springMVC+mybatis的使用,dubbozookeeper

編輯:JAVA綜合教程

dubbo+zookeeper+spring+springMVC+mybatis的使用,dubbozookeeper


讀前聲明:由於本人水平有限,有錯誤或者描述不恰當的地方請指出來,勿噴!第一次寫博客。

 源碼下載鏈接:http://files.cnblogs.com/files/la-tiao-jun-blog/dubbo%E4%BE%8B%E5%AD%90.rar

使用條件:

     eclipse-jee-luna-SR2-win32-x86_64

     jdk1.7,Apache Tomcat v8.0,maven

     zookeeper3.4.6

     dubbo-2.4.10

     dubbo-monitor-simple-2.5.4-SNAPSHOT-assembly.tar.gz(dubbo簡易監控中心)

服務提供者的工程目錄(下左):                               服務消費者的工程目錄(下右):

         

 

服務提供者的pom.xml:

banksteel-yesen:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>bankmineral</groupId>
  <artifactId>banksteel-yesen</artifactId>
   <packaging>pom</packaging>
  <version>0.0.1-SNAPSHOT</version>

  <name>banksteel-yesen</name>
  <url>http://maven.apache.org</url>

  <!-- 對項目的banksteel-yesen、banksteel-yesen-api、banksteel-yesen-provider這三個模塊進行聚合 -->
  <modules>
    <module>../banksteel-yesen-api</module>
    <module>../banksteel-yesen-provider</module>
  </modules>
  
  <dependencyManagement>
      <dependencies>
         <dependency>
           <groupId>bankmineral</groupId>
           <artifactId>banksteel-user-api</artifactId>
           <!-- 訪問maven.version屬性 -->
           <version>${maven.version}</version>
           <scope>compile</scope>
        </dependency>
        <dependency>
           <groupId>bankmineral</groupId>
           <artifactId>banksteel-user-provider</artifactId>
           <!-- 訪問maven.version屬性 -->
           <version>${maven.version}</version>
        </dependency>  
  </dependencies>
  </dependencyManagement>
</project>
View Code

banksteel-yesen-api:

<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>bankmineral</groupId>
  <artifactId>banksteel-yesen-api</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>banksteel-yesen-api</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- spring版本號 -->
        <spring.version>4.0.2.RELEASE</spring.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.2.6</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.7.7</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>
    <parent>  
       <groupId>bankmineral</groupId>
       <artifactId>banksteel-yesen</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <!-- 使用相對路徑 -->
       <relativePath>../banksteel-yesen/pom.xml</relativePath>  
  </parent>
  <dependencies>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </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-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</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-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</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>
            <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.12</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.12</version>
        </dependency>    
         <dependency>  
                <groupId>org.javassist</groupId>  
                <artifactId>javassist</artifactId>  
                <version>3.18.1-GA</version>  
           </dependency> 
        <dependency>
              <groupId>org.jboss.netty</groupId>
              <artifactId>netty</artifactId>
              <version>3.2.5.Final</version>
        </dependency>
        <dependency>
              <groupId>org.apache.zookeeper</groupId>
              <artifactId>zookeeper</artifactId>
              <version>3.4.6</version>
        </dependency>    
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>  
            </dependency>
            <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
            <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>
        <!-- log end -->      
  </dependencies>

</project>
View Code

banksteel-yesen-provider:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>bankmineral</groupId>
  <artifactId>banksteel-yesen-provider</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>banksteel-yesen-provider Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>  
       <groupId>bankmineral</groupId>
       <artifactId>banksteel-yesen</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <!-- 使用相對路徑 -->
       <relativePath>../banksteel-yesen/pom.xml</relativePath>  
  </parent>

  <dependencies>
    <dependency>
         <groupId>bankmineral</groupId>
          <artifactId>banksteel-yesen-api</artifactId>
           <version>0.0.1-SNAPSHOT</version>
    </dependency> 
   
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 導入java ee jar 包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <!-- 導入Mysql數據庫鏈接jar包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- JSTL標簽類 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!-- 格式化對象,方便輸出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>

        <!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- 上傳組件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>    
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.4.10</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.4</version>
    </dependency>
  </dependencies>
  <build>
          <resources>
            <resource>
                <targetPath>${project.build.directory}/classes</targetPath>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                <include>**/*.xml</include>
                <include>*.properties</include>
                </includes>
            </resource>
            <!-- 結合com.alibaba.dubbo.container.Main -->
            <resource>
                <targetPath>${project.build.directory}/classes/META-INF/spring</targetPath>
                <directory>src/main/resources/spring</directory>
                <filtering>true</filtering>
                <includes>
                    <include>spring-mybatis.xml</include>
                </includes>
            </resource>
        </resources>
        
        <pluginManagement>
            <plugins>
                <!-- 解決Maven插件在Eclipse內執行了一系列的生命周期引起沖突 -->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-dependency-plugin</artifactId>
                                        <versionRange>[2.0,)</versionRange>
                                        <goals>
                                            <goal>copy-dependencies</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <!-- 打包jar文件時,配置manifest文件,加入lib包的jar依賴 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <classesDirectory>target/classes/</classesDirectory>
                    <archive>
                        <manifest>
                            <mainClass>com.alibaba.dubbo.container.Main</mainClass>
                            <!-- 打包時 MANIFEST.MF文件不記錄的時間戳版本 -->
                            <useUniqueVersions>false</useUniqueVersions>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <type>jar</type>
                            <includeTypes>jar</includeTypes>
                            <useUniqueVersions>false</useUniqueVersions>
                            <outputDirectory>
                                ${project.build.directory}/lib
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
View Code

服務消費者的pom.xml

banksteel-user-app:

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
  <groupId>bankmineral</groupId>
  <artifactId>banksteel-userapp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>banksteel-userapp Maven Webapp</name>
  <url>http://maven.apache.org</url>

    <parent>
        <groupId>bankmineral</groupId>
        <artifactId>banksteel-yesen</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>bankmineral</groupId>
        <artifactId>banksteel-yesen-api</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

    <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dubbo</artifactId>
            <version>2.4.10</version>
        </dependency>
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.4</version>
    </dependency>
    <!-- JSTL標簽類 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
  </dependencies>
  <build>
    <finalName>banksteel-user-app</finalName>
  </build>
</project>
View Code

服務提供者的java代碼:

-----------banksteel-yesen-api-------------

com.yesen.entity

package com.yesen.entity;

import java.io.Serializable;

public class User implements Serializable{
    private long id;
    private String username;
    private String password;
    private int age;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
View Code

com.yesen.service

package com.yesen.service;

import java.util.List;
import java.util.Map;

import com.yesen.entity.User;

public interface UserService {

    List<User> getUserByMap(Map<String, Object> paramMap);

    void insertUser(User user);
}
View Code

--------banksteel-yesen-provider-------------

com.yesen.dao

package com.yesen.dao;

import java.util.List;
import java.util.Map;

import com.yesen.entity.User;

public interface UserDAO {

    List<User> getUserByMap(Map<String, Object> paramMap);

    void insertUser(User user);
}
View Code

com.yesen.dao.impl

package com.yesen.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.yesen.dao.UserDAO;
import com.yesen.entity.User;

@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

    private static final String INSERT = "com.yesen.model.userMapper.insertUser";

    private static final String LISTBY = "com.yesen.model.userMapper.listBy";

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public List<User> getUserByMap(Map<String, Object> paramMap) {

        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();

        return session.selectList(LISTBY, paramMap);
    }

    public void insertUser(User user) {

        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession();

        session.insert(INSERT, user);
    }
}
View Code

com.yesen.service.impl

package com.yesen.service.impl;

import java.util.List;
import java.util.Map;

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

import com.yesen.dao.UserDAO;
import com.yesen.entity.User;
import com.yesen.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    public List<User> getUserByMap(Map<String, Object> paramMap) {
        
        return userDAO.getUserByMap(paramMap);
    }

    public void insertUser(User user) {
        
        userDAO.insertUser(user);
    }
}
View Code

服務提供者的其他配置:

目錄結構只看src/main/resources

 

userMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yesen.model.userMapper">

<sql id="user">user</sql>
<!-- 結果集定義 -->
    <resultMap id="userMap" type="user">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="age" property="age" />
    </resultMap>

    <sql id="base_column_list">
        ID, USERNAME, PASSWORD, AGE
    </sql>

    <!-- 新增操作 -->
    <insert id="insertUser" parameterType="user" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO
        <include refid="user" />
        (USERNAME, PASSWORD, AGE)
        VALUES
        (#{username},#{password}, #{age})
    </insert>

<!-- 通過參數MAP獲取會員附件信息對象列表 -->
    <select id="listBy" parameterType="map" resultMap="userMap">
        SELECT
        <include refid="base_column_list" />
        FROM
        <include refid="user" />
        <where>
            <include refid="condition_sql" />
        </where>
        ORDER BY id DESC
        <if test="rowNum != null">
            LIMIT #{rowNum}
        </if>
    </select>

<!-- 查詢條件where語句塊 -->
    <sql id="condition_sql">
        <if test="username != null">
            AND USERNAME = #{username}
        </if>
        <if test="password != null">
            AND PASSWORD = #{password}
        </if>
    </sql>
    </mapper>
View Code

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <!-- 這個配置使全局的映射器啟用或禁用 緩存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局啟用或禁用延遲加載。當禁用時, 所有關聯對象都會即時加載 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 允許或不允許多種結果集從一個單獨 的語句中返回(需要適合的驅動) -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 使用列標簽代替列名。 不同的驅動在這 方便表現不同。 參考驅動文檔或充分測 試兩種方法來決定所使用的驅動 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 允許 JDBC 支持生成的鍵。 需要適合的 驅動。 如果設置為 true 則這個設置強制 生成的鍵被使用, 盡管一些驅動拒絕兼 容但仍然有效(比如 Derby) -->
        <setting name="useGeneratedKeys" value="false" />
        <!-- 配置默認的執行器。SIMPLE 執行器沒 有什麼特別之處。REUSE 執行器重用 預處理語句。BATCH 執行器重用語句 和批量更新 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!-- 設置超時時間, 它決定驅動等待一個數 據庫響應的時間 -->
        <setting name="defaultStatementTimeout" value="100" />
        <setting name="safeRowBoundsEnabled" value="false" />
        <setting name="mapUnderscoreToCamelCase" value="false" />
        <setting name="localCacheScope" value="SESSION" />
        <setting name="jdbcTypeForNull" value="OTHER" />
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
    </settings>

    <typeAliases>
        <typeAlias alias="user" type="com.yesen.entity.User" />
    </typeAliases>
</configuration>
View Code

dubbo-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:context="http://www.springframework.org/schema/context" 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://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://code.alibabatech.com/schema/dubbo
         http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 具體的實現bean -->
    <bean id="userService" class="com.yesen.service.impl.UserServiceImpl"></bean>
    <dubbo:application name="banksteel-user-provider"  />
     <!-- 使用zookeeper廣播注冊中心暴露服務地址 -->
    <dubbo:registry address="localhost:2181" protocol="zookeeper"/>
    <!-- 用dubbo協議在20880端口暴露服務 -->
    <dubbo:protocol name="dubbo" port="20880" id="mydubbo"/>

    <dubbo:service interface="com.yesen.service.UserService" ref="userService"></dubbo:service>

</beans>
View Code

spring-mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 自動掃描 -->
    <context:component-scan base-package="com.yesen"></context:component-scan>
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 初始化連接大小 -->
        <property name="initialSize" value="${jdbc.initialSize}"></property>
        <!-- 連接池最大數量 -->
        <property name="maxActive" value="${jdbc.maxActive}"></property>
        <!-- 連接池最大空閒 -->
        <property name="maxIdle" value="${jdbc.maxIdle}"></property>
        <!-- 連接池最小空閒 -->
        <property name="minIdle" value="${jdbc.minIdle}"></property>
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="${jdbc.maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mybatis/mapper/*Mapper.xml"/>
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="close" scope="prototype">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <import resource="classpath:spring/dubbo-service.xml"/>
</beans>
View Code

 服務消費者的java代碼:

com.yesen.controller

package com.yesen.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yesen.entity.User;
import com.yesen.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/create")
    public String createUser(HttpServletRequest request, Model model){
        
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String age =request.getParameter("age");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAge(Integer.parseInt(age));
        userService.insertUser(user);
        model.addAttribute("message", user.getUsername());

        return "insertSuccess";
    }

    @RequestMapping(value = "/query")
    public String queryUser(String username, Model model,HttpServletRequest request){

        Map<String, Object> paramMap = new HashMap<String, Object>();
        
        List<User> userList = userService.getUserByMap(paramMap);
        System.out.println("------------");
        for(User user: userList){
            System.out.println("姓名:"+user.getUsername()+"  ,密碼:"+user.getPassword());
        }

        model.addAttribute(userList);

        return "userInfo";
    }
}
View Code

服務消費者的其他配置:

注:服務消費者工程目錄中的dubbo.properties沒有用到,請忽略。

dubbo-user.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns: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://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://code.alibabatech.com/schema/dubbo
         http://code.alibabatech.com/schema/dubbo/dubbo.xsd"
         default-autowire="byName">
    
    <dubbo:application name="banksteel-userapp"  />
 
    <dubbo:registry address="zookeeper://localhost:2181" protocol="zookeeper"/>

    <dubbo:reference interface="com.yesen.service.UserService" id="userService" check="false" timeout="10000"/>
    
</beans>
View Code

root-config.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.yesen.controller" />
<import resource="classpath:META-INF/spring/dubbo-user.xml" />
View Code

spring-mvc.xml:

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

<!-- 自動掃描該包,使SpringMVC認為包下用了@controller注解的類是控制器 -->
    <context:component-scan base-package="com.yesen.controller" />
    
    <!--避免IE執行AJAX時,返回JSON出現下載文件 -->
    <!-- <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean> -->
    <!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射 -->
    <!-- <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />    JSON轉換器
            </list>
        </property>
    </bean> -->
    <!-- 定義跳轉的文件的前後綴 ,視圖模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的配置我的理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>
View Code

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:META-INF/spring/root-config.xml</param-value>  
    </context-param>  
    <!-- 編碼過濾器 -->  
    <filter>  
        <filter-name>encodingFilter</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>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- Spring監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring內存溢出監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
  
    <!-- Spring MVC servlet -->  
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:META-INF/spring/spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此處可以可以配置成*.do,對應struts的後綴習慣 -->  
        <url-pattern>/</url-pattern>  
    </servlet-mapping> 
   
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list> 
</web-app>
View Code

 windows下運行項目:

1.啟動zookeeper:找到zookeeper的bin目錄,雙擊zkServer.cmd。執行完效果如下:

 

(注:我的第二步,啟動dubbo服務,用執行jar的方式啟動,比較繁瑣。並不適用,最好是改變pom文件,打包編譯的配置,用到assembly,install之後,把.tar.gz包上傳到服務器,解壓,裡面就包含了lib目錄,直接運行類似於./start.sh start命令就好了,不用像我這樣啟動dubbo服務,可我一直沒搞出來,知道的請告訴我,再此先謝謝大神)

2.啟動dubbo服務:選中banksteel-yesen(服務提供方)右鍵--->Run As---> Maven clean--->Maven install一下。

沒有報錯的話,在target目錄下找到banksteel-yesen-provider-0.0.1-SNAPSHOT.jar 和 lib,然後一起copy出來,比如放d盤下,執行jar。  

命令: java -jar banksteel-yesen-provider-0.0.1-SNAPSHOT.jar

 

我們看到dubbo服務已經啟動了。

3.連接zookeeper客戶端,我們可以看到會多出一個/dubbo節點。

雙擊zkCli.cmd,然後輸入 h ,按enter鍵,然後查看zookeeper的一些命令。

4.啟動服務消費者web工程。

tomcat啟動,我就不說了,運行的效果如下:

5.dubbo監控中心的使用:

dubbo-monitor-simple-2.5.4-SNAPSHOT-assembly.tar.gz  解壓後。進入conf目錄,找到dubbo.properties,編輯,保存。

進入bin目錄,雙擊start.bat。

然後打開浏覽器,輸入: http:locahost:8080/services.html。  (localhost其實是zookeeper服務器的地址),效果如下:

由上圖可了解有哪些dubbo服務,以及服務的消費情況。

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved