Dubbo的学习与总结(二)- -使用Dubbo

在上一篇中,我们对Dubbo有了一个大概的认识,现在我们来说如何使用。Dubbo的服务发现和使用是基于注册中心的,推荐使用zookeeper作为注册中心,注册中心的安装参考:http://blog.csdn.net/lf_214/article/details/50998910
Dubbo是一个面向服务的治理方案,那首先我们要有服务,还要定义出服务之间的规范,说到规范,我们就想到了Java中的接口,接口就是我们提供的规范。不论是服务调用方还是服务使用方,都要依照这个规范来使用。所以,规范应该是独立的。我们以用户服务为例,采用Maven来构建一个项目。

1.项目结构:

d-parent
d-facade
d-provider
d-client

2.父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.0modelVersion>

  <groupId>com.umsgroupId>
  <artifactId>d-parentartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>pompackaging>

  <name>d-parentname>
  <url>http://maven.apache.orgurl>

  <modules>
        <module>../d-clientmodule>
        <module>../d-facademodule>
        <module>../d-providermodule>
  modules>

  <properties>
     
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <jdk.version>1.6jdk.version>
  properties>

  <dependencyManagement>
      <dependencies>
        
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>3.2.8.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>3.2.8.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.10version>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-coreartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>jcl-over-slf4jartifactId>
            <version>1.7.10version>
        dependency>
        

        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>dubboartifactId>
            <version>2.5.3version>
            <exclusions>  
                <exclusion>  
                    <groupId>org.springframeworkgroupId>  
                    <artifactId>springartifactId>  
                exclusion>  
            exclusions> 
        dependency>
        

        
        <dependency>
            <groupId>com.github.sgroschupfgroupId>
            <artifactId>zkclientartifactId>
            <version>0.1version>
        dependency>
        <dependency>
            <groupId>org.apache.zookeepergroupId>
            <artifactId>zookeeperartifactId>
            <version>3.4.6version>
        dependency>
        
        
        <dependency>
            <groupId>org.jboss.nettygroupId>
            <artifactId>nettyartifactId>
            <version>3.2.5.Finalversion>
        dependency>
        

        
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>4.11version>
          <scope>testscope>
        dependency>

      dependencies>
  dependencyManagement>


  <build>
    <finalName>${project.artifactId}finalName>
    <resources>
        <resource>
            <targetPath>${project.build.directory}/classestargetPath>
            <directory>src/main/resourcesdirectory>
            <filtering>truefiltering>
            <includes>
                <include>**/*.xmlinclude>
                <include>**/*.propertiesinclude>
            includes>
        resource>

    resources>
    <testResources>
        <testResource>
            <directory>src/test/resourcesdirectory>
            <filtering>truefiltering>
        testResource>
    testResources>
    <plugins>
        
        <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-resources-pluginartifactId>
            <version>2.7version>
            <configuration>
                <encoding>${project.build.sourceEncoding}encoding>
            configuration>
        plugin>
        
        <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-compiler-pluginartifactId>
            <configuration>
                <source>${jdk.version}source>
                <target>${jdk.version}target>
                <encoding>${project.build.sourceEncoding}encoding>
            configuration>
        plugin>
    plugins>
    <pluginManagement>
        <plugins>
            
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
            plugin>
        plugins>
    pluginManagement>
  build>
project>

3.定义规范d-facade

package com.ums.facade;

import com.ums.dto.UserRequest;
import com.ums.dto.UserResponse;

public interface IUserQueryFacade {

    public UserResponse queryUser(UserRequest userRequest);

    public UserResponse queryAllUser();
}

package com.ums.dto;

import java.io.Serializable;

public class UserRequest implements Serializable{

    /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ 
    private static final long serialVersionUID = -8315084174735728065L;

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Override
    public String toString() {
        return "UserRequest [userId=" + userId + "]";
    }


}

package com.ums.dto;

import java.io.Serializable;

public class UserResponse implements Serializable{

    /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ 
    private static final long serialVersionUID = 1148480200357449237L;

    private String code;

    private String msg;

    public void setCode(String code){
        this.code = code;
    }

    public String getCode(){
        return code;
    }

    public void setMsg(String msg){
        this.msg = msg;
    }

     public String getMsg(){
        return msg;
    }


    @Override
    public String toString() {
        return "UserResponse [code=" + code+ " ,msg="+msg+"]";
    }

}

4.按照规范编写服务

package com.ums.facade.impl;

import org.springframework.stereotype.Service;

import com.ums.dto.UserRequest;
import com.ums.dto.UserResponse;
import com.ums.facade.IUserQueryFacade;

@Service("userQuery")
public class UserQueryFacadeImpl implements IUserQueryFacade{

    public UserResponse queryUser(UserRequest userRequest) {
        UserResponse userResponse = new UserResponse();
        String userId = userRequest.getUserId();
        System.out.println("查询用户userId:"+userId);
        userResponse.setCode("000");
        userResponse.setMsg("成功");
        return userResponse;
    }

    public UserResponse queryAllUser() {
        UserResponse userResponse = new UserResponse();
        userResponse.setCode("000");
        userResponse.setMsg("成功");
        return userResponse;
    }
}

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">


    
    
    <dubbo:application name="dubbo-provider-ums" logger="slf4j"/>
    
    <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>

    
    <dubbo:protocol name="dubbo" port="20880"/>

    
    <dubbo:provider timeout="10000" threadpool="fixed" threads="100" accepts="1000" />

    
    <dubbo:service interface="com.ums.facade.IUserQueryFacade" ref="userQuery" protocol="dubbo"/>
beans>

5.按照规范编写客户端调用

package com.ums.client;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ums.dto.UserRequest;
import com.ums.dto.UserResponse;
import com.ums.facade.IUserQueryFacade;



/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        IUserQueryFacade userQuery = (IUserQueryFacade) context.getBean("userQuery");

        UserRequest userRequest = new UserRequest();
        userRequest.setUserId("123");
        UserResponse userResponse = userQuery.queryUser(userRequest);
        System.out.println("响应结果:"+userResponse);
        context.close();
    }
}

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">


    
    
    <dubbo:application name="dubbo-consumer-ums" logger="slf4j"/>
    
    <dubbo:registry protocol="zookeeper" address="127.0.0.1:2181"/>

    
    <dubbo:reference interface="com.ums.facade.IUserQueryFacade" id="userQuery" check="false"/>
    
    <dubbo:consumer timeout="6000"/>

beans>

6.启动服务

package com.ums.provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/** * 启动dubbo服务 * @author liufei * @date 2016-3-28 */
public class DubboProvider {

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

    public static void main(String[] args) {
        try {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
            context.start();
        } catch (Exception e) {
            log.error("== DubboProvider context start error:",e);
        }
        synchronized (DubboProvider.class) {
            while (true) {
                try {
                    DubboProvider.class.wait();
                } catch (InterruptedException e) {
                    log.error("== synchronized error:",e);
                }
            }
        }
    }

}

7.执行客户端调用,可以看到客户端打印成功的日志信息。项目的源码已经上传:http://download.csdn.net/detail/lf_214/9474592

你可能感兴趣的:(Dubbo)