dubbo+zookeeper 简单实现远程接口调用

说明:这里只简单演示使用dubbo远程调用框架实现接口调用,zookeeper安装到本地测试

项目说明:

com.maven.api:公用api,这里只存放最基本的service接口,以及实体类,pom.xml中需要引入dubbo+zookeeper 依赖包

com.maven.core:服务提供方,也是数据库访问层,实现业务逻辑,需要引入com.maven.api依赖

com.maven.consumer:服务调用方,web项目,对外开放访问权限,需要引入com.maven.api依赖


一,com.maven.api 项目

(一) 引入依赖包,pom.xml 配置文件如下:

<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.maven.dubbo</groupId>
  <artifactId>com.maven.api</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  	     <dependency>
				<groupId>com.alibaba</groupId>
				<artifactId>dubbo</artifactId>
				<version>2.5.3</version>
				<exclusions>
					<exclusion>
						<groupId>org.springframework</groupId>
						<artifactId>spring</artifactId>
					</exclusion>
				</exclusions>
		 </dependency>
		 <dependency>
				<groupId>com.101tec</groupId>
				<artifactId>zkclient</artifactId>
				<version>0.7</version>
		 </dependency>
  </dependencies>
</project>

(二) 新建UserService

package com.maven.facade;

import java.util.List;

import com.maven.entity.UserInfo;

public interface UserService {

	Integer insert(UserInfo userInfo);

	Integer delete(Long uid);

	UserInfo select(Long uid);

	/** 获取用户信息集合 */
	List<UserInfo> listUserInfo();


}
(三) 新建实体类对应数据库user_info表
package com.maven.entity;

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

public class UserInfo implements Serializable{
	private static final long serialVersionUID = 5775086719909153531L;

	private Long id;

    private String userName;

    private String password;

    private String email;

    private String phone;

    private String sex;

    private String status;

    private Date createTime;

    private Date updateTime;

    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 == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status == null ? null : status.trim();
    }

    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;
    }

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", userName=" + userName + ", password=" + password + ", email=" + email
				+ ", phone=" + phone + ", sex=" + sex + "]";
	}

    
    
}
二,com.maven.core

使用sping+mybatis+mysql构建项目,前面已经介绍过相关框架,这里不多介绍

不熟悉的同学可以跳转查看:http://blog.csdn.net/mynoteblog/article/details/54922775
(一) pom.xml 引入相关依赖

<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.maven.dubbo</groupId>
  <artifactId>com.maven.core</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
		<spring.version>4.3.0.RELEASE</spring.version>
		<mybatis.version>3.3.0</mybatis.version>
		<mybatis-spring.version>1.2.3</mybatis-spring.version>
		<mysql.connector.version>5.1.29</mysql.connector.version>
	</properties>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
	    	<groupId>com.maven.dubbo</groupId>
			<artifactId>com.maven.api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
	    </dependency>
	
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- @Resource注解包 -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</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-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- 数据库连接池 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- mybatis start -->
		<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>org.mybatis</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>

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

	</dependencies>
</project>
(二) 配置Spring-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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
          
	<!-- 扫描注解 -->
	<context:component-scan base-package="com.maven.core">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 1. 数据源 : DriverManagerDataSource -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/yun?characterEncoding=utf8" />
		<property name="username" value="root" />
		<property name="password" value="centos" />
		<!-- 从池中获取连接前进行验证 -->
		<property name="testOnBorrow" value="false" />
		<!-- 向池中还回连接前进行验证 -->
		<property name="testOnReturn" value="false" />
		<!-- 连接空闲时验证 -->
		<property name="testWhileIdle" value="true" />
		<!-- 运行判断连接超时任务(evictor)的时间间隔,单位为毫秒,默认为-1,即不执行任务。 -->
		<property name="timeBetweenEvictionRunsMillis" value="300000" />
		<!-- 连接的超时时间,默认为半小时。 -->
		<property name="minEvictableIdleTimeMillis" value="1800000" />
		<!-- 每次evictor启动检查的空闲连接数,-2标识1/2的总空闲连接 -->
		<property name="numTestsPerEvictionRun" value="-1"></property>
		<!-- 线程池初始数量 -->
		<property name="initialSize" value="10"></property>
		<!-- 最大线程数量 -->
		<property name="maxActive" value="50"></property>
		<!-- 最大空闲线程数量 -->
		<property name="maxIdle" value="20"></property>
		<!-- 最小空闲线程数量 -->
		<property name="minIdle" value="10"></property>
		<!-- 从线程池获取一个mysql连接的最大等待时间,单位毫秒 -->
		<property name="maxWait" value="1000"></property>
	</bean>

	<!-- 2. mybatis的SqlSession的工厂-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 所有配置的mybatis映射文件 -->
		<property name="mapperLocations" value="classpath*:com/maven/core/mapping/*.xml" />
	</bean>

	<!-- 3. mybatis自动扫描加载Sql接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.maven.core.mapper"></property>
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>

	<!-- 4. 事务管理  -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

	<import resource="classpath:Spring-dubbo.xml" />
</beans>

(三) 配置Spring-dubbo.xml,配置注册中心地址,暴露dubbo服务

这里使用的是安装在本地的zookeeper,启动项目前需要先启动zookeeper,默认端口2181

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
        
    <!-- 提供方应用信息,用于计算依赖关系 -->
	<dubbo:application name="dubbo_provider" organization="com_maven_dubbo" />

	<!-- 使用zookeeper注册中心暴露服务地址 -->
	<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" />

	<!-- 用dubbo协议在20880端口暴露服务 -->
	<dubbo:protocol name="dubbo" port="20880" />

	<import resource="classpath:dubbo-provider.xml" />
</beans>

(四) 配置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:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

	<!-- 声明需要暴露的服务接口 -->
	<dubbo:service interface="com.maven.facade.UserService" ref="userService" >
        <dubbo:method name="insert" timeout="10000" retries="0" />
        <dubbo:method name="delete" timeout="10000" retries="0" />
        <dubbo:method name="select" timeout="10000" retries="0" />
        <dubbo:method name="listUserInfo" timeout="100000" retries="0" />
    </dubbo:service>
    
</beans>
这里需要注意:ref="userService" 接口名需要对应到userServiceImpl,

本例采用注解方式配置,如下配置@Service("userService")
(五) 新建UserServiceImpl实现UserService接口

package com.maven.core.facade.impl;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.maven.core.mapper.UserInfoMapper;
import com.maven.entity.UserInfo;
import com.maven.facade.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	
	@Resource
	private UserInfoMapper userInfoMapper;
	
	public Integer insert(UserInfo userInfo) {
		return userInfoMapper.insertSelective(userInfo);
	}

	public Integer delete(Long uid) {
		return userInfoMapper.deleteByPrimaryKey(uid);
	}

	public UserInfo select(Long uid) {
		System.out.println("............");
		return userInfoMapper.selectByPrimaryKey(uid);
	}

	public List<UserInfo> listUserInfo() {
		System.out.println(".............");
		List<UserInfo> list = userInfoMapper.selectAll();
		return list;
	}

}
(六) UserInfoMapper
package com.maven.core.mapper;

import java.util.List;
import org.springframework.stereotype.Repository;

import com.maven.entity.UserInfo;

@Repository
public interface UserInfoMapper {
    int deleteByPrimaryKey(Long id);

    int insert(UserInfo record);

    int insertSelective(UserInfo record);

    UserInfo selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(UserInfo record);

    int updateByPrimaryKey(UserInfo record);

	List<UserInfo> selectAll();


}
(七) UserInfoMapper.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.maven.core.mapper.UserInfoMapper" >
  <resultMap id="BaseResultMap" type="com.maven.entity.UserInfo" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="status" property="status" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, password, email, phone, sex, status, create_time, update_time
  </sql>
  <select id="selectAll" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from user_info
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from user_info
    where id = #{0}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from user_info
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.maven.entity.UserInfo" >
    insert into user_info (id, user_name, password, 
      email, phone, sex, 
      status, create_time, update_time
      )
    values (#{id,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, 
      #{status,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.maven.entity.UserInfo" >
    insert into user_info
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="email != null" >
        email,
      </if>
      <if test="phone != null" >
        phone,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="status != null" >
        status,
      </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=BIGINT},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        #{status,jdbcType=VARCHAR},
      </if>
      <if test="createTime != null" >
        now(),
      </if>
      <if test="updateTime != null" >
        now(),
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.maven.entity.UserInfo" >
    update user_info
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="phone != null" >
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="status != null" >
        status = #{status,jdbcType=VARCHAR},
      </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=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.maven.entity.UserInfo" >
    update user_info
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      status = #{status,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>
(八) 启动服务,这里在main函数加载启动
package com.maven.core.provider;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 启动Spring容器
 * @author Administrator
 *
 */
public class Provider {

	public static void main(String[] args) throws IOException {
		String[] files = new String[]{"classpath:Spring-config.xml"};
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(files);
		context.registerShutdownHook();
		context.start();
		CountDownLatch latch = new CountDownLatch(1);
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
			// 为保证服务一直开着,利用输入流的阻塞来模拟
			System.in.read();
		}
	}
}

三,com.maven.consumer

(一) 引入相关依赖,pom.xml

<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>com.maven.dubbo</groupId>
  <artifactId>com.maven.consumer</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>com.maven.consumer Maven Webapp</name>
  
  <properties>
		<spring.version>4.3.0.RELEASE</spring.version>
		<jackson.version>2.6.5</jackson.version>
		<fastjson.version>1.2.23</fastjson.version>
		<mybatis.version>3.3.0</mybatis.version>
		<mybatis-spring.version>1.2.3</mybatis-spring.version>
		<mysql.connector.version>5.1.29</mysql.connector.version>
		<jedis.version>2.7.3</jedis.version>
		<spring.data.redis.version>1.7.1.RELEASE</spring.data.redis.version>
		<shiro.version>1.2.4</shiro.version>
		<slf4j.version>1.7.21</slf4j.version>
	</properties>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>Version99</id>
			<name>Version 99 Does Not Exist Maven repository</name>
			<layout>default</layout>
			<url>http://no-commons-logging.zapto.org/mvn2</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
	    	<groupId>com.maven.dubbo</groupId>
			<artifactId>com.maven.api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
	    </dependency>

		<!-- @Resource注解包 -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</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-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

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

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- slf4j日志框架 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.1.3</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.logback-extensions</groupId>
			<artifactId>logback-ext-spring</artifactId>
			<version>0.1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>99.0-does-not-exist</version>
		</dependency>

		<dependency>
			<groupId>com.maven.dubbo</groupId>
			<artifactId>com.maven.api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
	</dependencies>
	
  <build>
    <finalName>com.maven.consumer</finalName>
  </build>
  
</project>
(二) 相关配置文件:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">

	<!-- 设置Spring容器加载所有的配置文件的路径 --> 
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:Spring-config.xml</param-value>
	</context-param>
	
	<context-param>  
         <param-name>logbackConfigLocation</param-name>  
         <param-value>classpath:logback.xml</param-value>  
	</context-param>
	
	<!-- 防止内存泄露,放在所有监听器之前 -->   
	<listener>   
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>   
	</listener>
	
	<!-- 加载Spring容器配置 -->  
	<listener>  
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
	</listener>  
	
	<!-- 防止Spring内存溢出监听器 -->  
	<listener>  
	    <listener-class> org.springframework.web.context.ContextCleanupListener</listener-class>  
	</listener>
	
	<!-- logback监听器 -->
	<listener>  
	     <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>  
	</listener>
  
	<!-- 字符编码过滤器  -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 配置SpringMVC核心控制器 -->
	<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:Spring-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 项目启动首页 -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Spring-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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
          
	<!-- 扫描注解 -->
	<context:component-scan base-package="com.maven.consumer">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<import resource="classpath:Spring-dubbo.xml" />
</beans>

Spring-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-4.2.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

	<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
	<context:component-scan base-package="com.maven.consumer.controller" />

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean
				class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
				<description>JSON转换器</description>
				<property name="supportedMediaTypes">
					<list>
						<value>application/json;charset=UTF-8</value>
						<value>text/html;charset=UTF-8</value>
					</list>
				</property>
				<!-- 使用FastJson替代JackSon避免循环嵌套异常 -->
				<property name="features">
					<array>
						<value>QuoteFieldNames</value>
						<value>WriteDateUseDateFormat</value>
					</array>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

	<!-- 开启默认处理 -->
	<mvc:default-servlet-handler />

</beans>
Spring-dubbo.xml,服务调用方注册同一个zookeeper

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
        
     <!-- 提供方应用信息,用于计算依赖关系 -->
	<dubbo:application name="dubbo_consumer" />

	<!-- 和dubbo-provider使用同一个zookeeper注册中心 -->
	<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" />
	
	<import resource="classpath:dubbo-consumer.xml" />
</beans>
dubbo-consumer.xml,配置调用接口信息,与服务提供方配置相似,注意接口名一直

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
    
    <dubbo:reference interface="com.maven.facade.UserService" id="userService" >
        <dubbo:method name="insert" timeout="10000" retries="0" />
        <dubbo:method name="delete" timeout="10000" retries="0" />
        <dubbo:method name="select" timeout="10000" retries="0" />
        <dubbo:method name="listUserInfo" timeout="100000" retries="0" />
    </dubbo:reference>
    
</beans>
(三) 测试,UserController

package com.maven.consumer.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.maven.entity.UserInfo;
import com.maven.facade.UserService;


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

	@Resource
	private UserService userService;
	
	@ResponseBody
	@RequestMapping(value="/insert", method=RequestMethod.POST)
	public String insert(@RequestBody UserInfo userInfo){
		if(userInfo.getStatus()==null){
			userInfo.setStatus("0");
		}
		Integer count = userService.insert(userInfo);
		if(count>0){
			return "保存用户信息成功";
		}
		return "保存用户信息失败";
	}
	
	@ResponseBody
	@RequestMapping(value="/select", method=RequestMethod.GET)
	public String select(@RequestParam Long uid){
		UserInfo userInfo = userService.select(uid);
		if(userInfo!=null){
			return "您要查找的用户名是:"+userInfo.getUserName();
		}
		return "查找用户失败";
	}
	
	@ResponseBody
	@RequestMapping(value="/delete", method=RequestMethod.DELETE)
	public String delete(@RequestParam Long uid){
		Integer count = userService.delete(uid);
		if(count>0){
			return "删除用户信息成功";
		}
		return "删除用户信息失败";
	}
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public List<UserInfo> list(){
		System.out.println(".............");
		List<UserInfo> userInfos = userService.listUserInfo();
		return userInfos;
	}
	
}

四,项目构建完成,接下来是测试

(一) 启动zookeeper,在本地安装zookeeper后找到bin文件夹,开启zkServer.cmd

(二) 启动服务提供方,找到Provider.java,运行启动

(三) 启动服务调用方,将项目部署到tomcat,启动

(四) 调用测试:







测试成功,分享项目源码:http://pan.baidu.com/s/1jI7J802



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值