项目使用Dubbo实现解耦和

代码准备

本次作者建立了一个小Demo来说明如何使用Dubbo实现解耦和的项目部署方式
作者使用的开发工具是idea,大家也可以使用eclipse或者myeclipse.
首先使用idea创建一个maven项目,
项目使用Dubbo实现解耦和_第1张图片
其中包括了5个子模块,分别是
- dao
- daoimpl
- service
- serviceimpl
- web
项目结构如下图,请原谅画的比较…..(额..抽象)
项目使用Dubbo实现解耦和_第2张图片
最上面是dubbodemo的项目,旗下分为5个子模块.
他们的依赖关系分别如图所示
- daoimpl→dao
- serviceimpl→service
- serviceimpl→dao
- web→service

具体需要的jar包pom文件如下


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <properties>
        <spring.version>4.3.9.RELEASEspring.version> 
        <jedis.version>2.9.0jedis.version>
        <dubbo.version>2.5.5dubbo.version>
        <junit.version>4.12junit.version>
        <jackson.version>2.9.1jackson.version>
    properties>

    <groupId>com.dsjgroupId>
    <artifactId>dubbodemoartifactId>
    <version>1.0-SNAPSHOTversion>
    <modules>
        <module>daomodule>
        <module>daoimplmodule>
        <module>servicemodule>
        <module>serviceimplmodule>
        <module>webmodule>
    modules>
    <packaging>pompackaging>

    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>redis.clientsgroupId>
                <artifactId>jedisartifactId>
                <version>${jedis.version}version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>dubboartifactId>
                <version>${dubbo.version}version>
            dependency>
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>${junit.version}version>
                <scope>testscope>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-testartifactId>
                <version>${spring.version}version>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>${spring.version}version>
            dependency>
            
            <dependency>
                <groupId>com.fasterxml.jackson.coregroupId>
                <artifactId>jackson-databindartifactId>
                <version>${jackson.version}version>
            dependency>

        dependencies>
    dependencyManagement>

project>

Dao

首先我们来编写一下dao,比如用户使用dao提供的服务

public interface UserDao {
    int add(int i,int n);
}

显而易见,我们的dao只提供了一个add,下面编写daoimpl

DaoImpl

注:所有的模块均使用maven,包括打包
接下来是daoimpl的pom文件


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dubbodemoartifactId>
        <groupId>com.dsjgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>dao-implartifactId>
    <dependencies>
        <dependency>
            <groupId>com.dsjgroupId>
            <artifactId>daoartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
        dependency>
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>dubboartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
              <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-jar-pluginartifactId>
                <configuration>                    <classesDirectory>target/classes/classesDirectory>
                    <archive>
                        <manifest>
                            <mainClass>com.alibaba.dubbo.container.MainmainClass>
                            
                            <useUniqueVersions>falseuseUniqueVersions>
                            <addClasspath>trueaddClasspath>
                            <classpathPrefix>lib/classpathPrefix>
                        manifest>
                        <manifestEntries>
                            <Class-Path>.Class-Path>
                        manifestEntries>
                    archive>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-dependency-pluginartifactId>
                <executions>
                    <execution>
                        <id>copy-dependenciesid>
                        <phase>packagephase>
                        <goals>
                            <goal>copy-dependenciesgoal>
                        goals>
                        <configuration>
                            <type>jartype>
                            <includeTypes>jarincludeTypes>
                            
                            <outputDirectory>
                                ${project.build.directory}/lib
                            outputDirectory>
                        configuration>
                    execution>
                executions>
            plugin>
        plugins>
        <resources>
            <resource>
                <targetPath>${project.build.directory}/classestargetPath>
                <directory>src/main/resourcesdirectory>
                <filtering>truefiltering>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
            resource>
            
            <resource>
                <targetPath>${project.build.directory}/classes/META-INF/springtargetPath>
                <directory>src/main/resourcesdirectory>
                <filtering>truefiltering>
                <includes>
                    <include>spring-dao-impl.xmlinclude>
                includes>
            resource>
        resources>
    build>

project>

以及Spring的配置文件


<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">
<context:component-scan base-package="com.dsj"/>
    
    
    <dubbo:application name="dsj-dao"/>
    <dubbo:registry protocol="redis" address="192.168.201.113:6379" />
    <bean id="userDao" class="com.dsj.dao.UserDaoImpl"/>
    <dubbo:service interface="com.dsj.dao.UserDao" ref="userDao"/>

beans>

接下来是dao的实现类daoimpl,被调用之后会在控制台打印使用dubbo提供加法服务

import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.stereotype.Repository;

/**
 * Created by Administrator on 2017/9/20 0020.
 */
@Repository
@Service
public class UserDaoImpl implements UserDao{
    public int add(int i, int n) {
        System.out.println("使用dubbo提供加法服务");
        return i+n;
    }
}

同时 写一个运行时的类运行jar包时候自动执行该类的main方法

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 * Created by Administrator on 2017/9/24 0024.
 */
public class RunJar {
    public static void main(String[] args) throws IOException {
        if (args.length==0){
            System.err.println("Useage:java jar dao.1.0-SNAPSHOT.jar spring-dao-impl.xml");
        }else {
            ApplicationContext ac=new ClassPathXmlApplicationContext("args[0]");
            System.out.println("服务已启动,按回车停止");
            System.in.read();
        }
    }
}

ServiceImpl

接下来service不做过多的赘述和dao相同
serviceimpl中的spring-service-impl.xml文件如下


<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"
       xmlns:context="http://www.springframework.org/schema/context"
       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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.dsj"/>
    <dubbo:application name="dsj-service"/>
    <dubbo:registry protocol="redis" address="192.168.201.113:6379" />
    <dubbo:reference id="userDao" interface="com.dsj.dao.UserDao"/>
    <dubbo:protocol name="dubbo" port="20888"/>
    <bean id="userService" class="com.dsj.service.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    bean>
    <dubbo:service  interface="com.dsj.service.UserService" ref="userService"/>
beans>

以及pom文件中的设置


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dubbodemoartifactId>
        <groupId>com.dsjgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>service-implartifactId>
    <dependencies>
        <dependency>
            <groupId>com.dsjgroupId>
            <artifactId>serviceartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>com.dsjgroupId>
            <artifactId>daoartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>com.dsjgroupId>
            <artifactId>daoartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
        dependency>
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>dubboartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-jar-pluginartifactId>
                <configuration>
                    <classesDirectory>target/classes/classesDirectory>
                    <archive>
                        <manifest>
                            <mainClass>com.alibaba.dubbo.container.MainmainClass>
                            
                            <useUniqueVersions>falseuseUniqueVersions>
                            <addClasspath>trueaddClasspath>
                            <classpathPrefix>lib/classpathPrefix>
                        manifest>
                        <manifestEntries>
                            <Class-Path>.Class-Path>
                        manifestEntries>
                    archive>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-dependency-pluginartifactId>
                <executions>
                    <execution>
                        <id>copy-dependenciesid>
                        <phase>packagephase>
                        <goals>
                            <goal>copy-dependenciesgoal>
                        goals>
                        <configuration>
                            <type>jartype>
                            <includeTypes>jarincludeTypes>
                            
                            <outputDirectory>
                                ${project.build.directory}/lib
                            outputDirectory>
                        configuration>
                    execution>
                executions>
            plugin>
        plugins>
        <resources>
            <resource>
                <targetPath>${project.build.directory}/classestargetPath>
                <directory>src/main/resourcesdirectory>
                <filtering>truefiltering>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
            resource>
            
            <resource>
                <targetPath>${project.build.directory}/classes/META-INF/springtargetPath>
                <directory>src/main/resourcesdirectory>
                <filtering>truefiltering>
                <includes>
                    <include>spring-service-impl.xmlinclude>
                includes>
            resource>
        resources>
    build>
project>

当然少不了运行时的main方法

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by Administrator on 2017/9/24 0024.
 */
public class RunJar {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("spring-service-impl.xml");
        UserService us=ac.getBean(UserService.class);
        us.add(5,6);
    }
}

还有serviceimp

import com.dsj.dao.UserDao;

/**
 * Created by Administrator on 2017/9/20 0020.
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public int add(int i, int n) {
        System.out.println(String.format("开始计算%d+%d的结果,等待dubbo服务响应",i,n));
        int sum=userDao.add(i,n);
        System.out.println(sum);
        return sum;
    }
}

Web

最后一个模块web模块
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">
    <parent>
        <artifactId>dubbodemoartifactId>
        <groupId>com.dsjgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>webartifactId>
    <packaging>warpackaging>
    <dependencies>
        <dependency>
            <groupId>com.dsjgroupId>
            <artifactId>serviceartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
        dependency>
        <dependency>
            <groupId>redis.clientsgroupId>
            <artifactId>jedisartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>dubboartifactId>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
        dependency>
    dependencies>
project>

spring-webmvc.xml


<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: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://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<context:component-scan base-package="com.dsj"/> 
    <mvc:annotation-driven/>    
    <mvc:default-servlet-handler/>      
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    <dubbo:annotation/>
    <dubbo:application name="dsj-web"/>
    <dubbo:registry protocol="redis" address="192.168.201.113:6379" />
    <dubbo:reference interface ="com.dsj.service.UserService" id ="userService"/>

beans>

UserController

package com.dsj.controller;

import com.dsj.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/24 0024.
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/add")
    @ResponseBody
    public Map add(Integer i, Integer n) {
        Map data = new HashMap();
        int sum = userService.add(i, n);
        data.put("result", sum);
        return data;


    }
}

webapp/WEB-INF下的web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>spring-webmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-webmvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>spring-webmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

以及一个非常简单的页面


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.10.2.min.js">script>
    <script>
        $(function () {
            $('button').click(function () {
                var num1=$('#num1').val();
                var num2=$('#num2').val();
                $.get("add",{"i":num1,"n":num2},function (data) {
                    $('#rs').val(data.result);
                })
            })
        })
    script>
head>
<body>
<input type="number" id="num1">+<input type="number" id="num2"><button>=button><input type="number" id="rs">
body>
html>

项目结构如下
项目使用Dubbo实现解耦和_第3张图片

项目部署

首先使用idea的工具
项目使用Dubbo实现解耦和_第4张图片
daoimpl serviceimpl web 三个模块分别进行打包
除了web是war包意外 前两个均为jar包 我们的maven配置方式可以直接运行打包好的jar
接下来在磁盘上找到打包好的jar包
项目使用Dubbo实现解耦和_第5张图片
打开一个终端执行

java -jar dao-xxx.jar

serviceimpl同上
注意运行的顺序,第一个是daoimpl 然后serviceimpl 最后是tomcat
将web打包好的war包放在tomcat的webapp下 改名为ROOT如果之前使用过tomcat需要先将ROOT文件夹删除
就像这样
这里写图片描述
接下来运行tomcat的启动脚本
作者是在windows环境下运行所以启动的是bin目录下的startup.bat
其实这三个部分可以分别放在三台不同的主机上,也就是真正实现了代码的解耦
最后部署结构如下
项目使用Dubbo实现解耦和_第6张图片

你可能感兴趣的:(Java,dubbo)