三分钟学会就会的分布式服务框架dubbo

dubbo本地服务化实现

项目搭建(Maven项目管理方式):

① 创建公共项目工程:普通的Maven工程,提供utils、DO、接口的代码。

pom.xml 无任何依赖

② 创建服务提供者项目:普通的Maven工程(依赖Dubbo),提供服务实现、服务启动功能。

    pom.xml

<dependencies>
				<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.6.2</version>
		</dependency>
		<dependency>
			<groupId>dubbo-api</groupId>
			<artifactId>dubbo-api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
         <dependency>
    <groupId>com.github.sgroschupf</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.1</version>
</dependency>

		<!-- junit测试包 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.3.16.RELEASE</version>
		</dependency>

		
	</dependencies>

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-2.5.xsd
	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

	<dubbo:application name="dubbo-test-provider" owner="sampson"></dubbo:application>
	
	<dubbo:protocol name="dubbo" port="20880" ></dubbo:protocol>
	
	<!-- 局域网广播注册中心 -->
	<dubbo:registry address="multicast://239.5.6.7:1234" />
	
	<!-- 配置式发布 -->
	<bean id="userService" class="cn.itsource.dubbo.provider.service.UserServiceImpl"></bean>
	<dubbo:service interface="cn.itsource.dubbo.core.service.IUserService" ref="userService"></dubbo:service>
<!-- 注解式发布 -->
	<!-- 扫描注解包路径,多个包用逗号分隔,不填pacakge表示扫描当前ApplicationContext中所有的类 -->
	<dubbo:annotation package="cn.itsource.dubbo.provider.service" />
</beans>

启动服务监听

String configLocation = "classpath*:/dubbo-provider.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
System.out.println("dubbo-server服务正在监听,按任意键退出");
System.in.read();

服务消费者实现

创建服务消费者项目:普通的Maven工程(依赖Dubbo),完成服务调用功能。

    pom.xml

​
<dependencies>
	<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.6.2</version>
		</dependency>
<dependency>
			<groupId>dubbo-api</groupId>
			<artifactId>dubbo-api</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
   <dependency>
    <groupId>com.github.sgroschupf</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.1</version>
</dependency>
	</dependencies>

​

dubbo-consumer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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-2.5.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">

	<dubbo:application name="dubbo-test-consumer"></dubbo:application>
	
	<!-- 局域网广播注册中心 -->
	<dubbo:registry address="multicast://239.5.6.7:1234" />
		
	<!-- 配置式调用服务 -->
	<!-- <dubbo:reference id="helloService" interface="cn.itsource.dubbo.core.service.IHelloService"></dubbo:reference> -->
	
	<!-- 注解式调用服务 -->
	<!-- 扫描注解包路径,多个包用逗号分隔,不填pacakge表示扫描当前ApplicationContext中所有的类 -->
	<dubbo:annotation package="cn.itsource.dubbo.consumer" />
</beans>

JUnit4调用dubbo服务测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.dubbo.config.annotation.Reference;

import cn.itsource.dubbo.core.service.IHelloService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:/dubbo-consumer.xml"})
public class DubboServiceTest {
	@Reference
	private IHelloService helloService;
	
	@Test
	public void testHello(){
		String sayHi = helloService.sayHi("老宋");
		System.out.println(sayHi);
	}
}

直连调试模式

服务提供者:

修改注册中心为:N/A模式(不注册)

<dubbo:registry address="N/A" check="false"/> 

服务消费者:

修改注册中心为:N/A模式(不注册)

<dubbo:registry address="N/A" check="false"/>

url 配置属性

<dubbo:reference id="demoService" interface="cn.itsource.dubbo.DemoService"  url="dubbo://localhost:20881" />

配置本地调用地址映射:

然后在${user.home}/dubbo-resolve.properties文件中配置对应服务调用的本地地址

${user.home} 一般代表:C:\Users\{你当前登录名}

dubbo-resolve.properties示例

cn.itsource.dubbo.core.service.IUserService=dubbo://localhost:20880
cn.itsource.dubbo.core.service.IHelloService=dubbo://localhost:20880
.....其它服务配置

Dubbo服务打包

一.三种方式

1.使用Servlet容器(不用)

利用Tomcat、Jetty等WEB容器启动Dubbo服务。

缺点:增加管理配置的复杂性,不必要地使用http端口,浪费内存资源

2.Java的Main方法(不建议,本地调试可以用)

基于Spring框架,写一个Java类并提供Main方法启动。

缺点:无法使用Dubbo的一些高级特性,服务的管理需要自己额外提供实现

3.Dubbo框架Main方法

Dubbo框架本身提供了服务运行支持方法,基于com.alibaba.dubbo.container.Main

简单高效地运行服务

很好地支持Dubbo服务的发布、关停(ShutdownHook)

二.Maven编译打包

Pom.xml 
===================================================
<groupId>cn.itsource.service</groupId>
	<artifactId>service-user</artifactId>
	<version>${service-user.version}</version>
	<packaging>jar</packaging>
		
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<!-- 打包jar详细配置 -->
	<build>
		<!-- jar包名字 -->
		<finalName>provder</finalName>
		<!-- 打包资源配置,如配置文件 -->
		<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 
			官方文档:dubbo会自动在classes/META-INF/spring下去加载spring的配置文件
			因此打包时需要将spring配置文件复制到该目录
			-->
			<resource>
				<targetPath>${project.build.directory}/classes/META-INF/spring</targetPath>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<includes>
					<include>applicationContext.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>

	<dependencies>
	</dependencies>

dubbo服务jar包运行

Cmd窗口:

① 定位到jar包所在目录

② 输入命令并回车执行:java -jar xxxxx.jar

  1. P2P项目的分布式服务调用实现(crm)
    1. 分布式服务改造包含的内容

主要是对原有的代码进行重新整合,分为代码拆分、dubbo集成(分离出服务提供方和消费方)、服务发布与接入(注册中心zookeeper)

    1. 代码拆分

根据各层进行拆分,主要针对:

① pom.xml项目引用jar包

② 代码:DAO和Service层独立为服务提供者。前端和Controller独立为服务消费者。

③ Spring配置文件进行拆分(参考②步拆分思路)

注意:利用tomcat插件启动web需要设置tomcat的calsspath选中依赖的项目

Idea 需要

  

 <!-- 文件资源 -->

        <resources>

            <resource>

                <directory>src/main/java</directory>

                <includes>

                    <include>**/*.*</include>

                </includes>

                <excludes>

                    <exclude>**/*.java</exclude>

                </excludes>

                <filtering>false</filtering>

            </resource>

            <resource>

                <directory>src/main/resources</directory>

                <includes>

                    <include>**/*.*</include>

                </includes>

                <filtering>false</filtering>

            </resource>

        </resources>
    1. Dubbo集成

对服务提供方和服务消费者集成Dubbo的调用方式。

公共项目:

因为Dubbo涉及远程调用传输对象,所有需要传输的对象的类都必须实现Serializable接口,如Domain层的所有类。

      1. 服务提供方

① 修改原spring的@Service注解为dubbo的@Service注解

② 新建xxxx-dubbo-provider.xml,然后在spring contex的配置文件最后引入

   Xxxx-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服务发布 -->

<dubbo:application name="p2p-service" />

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

<dubbo:registry address="multicast://239.5.6.7:1236"></dubbo:registry>

<dubbo:annotation package="cn.itsource.eloan.core.service.impl" />

</beans>

③ 服务发布类


public class DubboServer {

public static void main(String[] args) throws IOException {

String configLocation = "classpath*:/spring-core.xml";

ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);

System.out.println("p2p服务正在监听,按任意键退出");

String[] names = context.getBeanDefinitionNames();

System.out.print("Beans:");

for (String string : names)

System.out.println(string);

System.out.println();

System.in.read();

}

}

① 修改需要远程调用的服务,从原spring的@Autoware注解为dubbo的@Reference注解服务消费方

② 新建xxxx-dubbo-consumer.xml,然后在springmvc contex的配置文件最后引入

   Xxxx-dubbo-consumer.xml示例

  1. Zookeeper注册中心
    1. 什么是Zookeeper

ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。

ZooKeeper的目标就是封装好复杂易出错的关键服务,将简单易用的接口和性能高效、功能稳定的系统提供给用户。

ZooKeeper包含一个简单的原语集, 提供Java和C的接口。

ZooKeeper代码版本中,提供了分布式独享锁、选举、队列的接口。其中分布锁和队列有Java和C两个版本,选举只有Java版本。

Zookeeper作为Dubbo服务的注册中心,Dubbo原先基于数据库的注册中心,没采用Zookeeper,Zookeeper是一个分布式的服务框架,是树型的目录服务的数据存储,能做到集群管理数据 ,这里能很好的作为Dubbo服务的注册中心,Dubbo能与Zookeeper做到集群部署,当提供者出现断电等异常停机时,Zookeeper注册中心能自动删除提供者信息,当提供者重启时,能自动恢复注册数据,以及订阅请求。我们先在windows上安装Zookeeper,我们安装最简单的单点,集群环境需要有兴趣的同学主动查找资料并利用虚拟机搭建。

2.修改注册中心地址

将集成好的项目,使用zookeeper替换multicast广播方式,作为dubbo服务的发布注册中心。

<dubbo:registry address="zookeeper://127.0.0.1:2181"></dubbo:registry>

 

3.安装zookeeper

① 官方下载地址http://mirrors.cnnic.cn/apache/zookeeper/

下载后获得,解压。

② 安装配置

  1. 把conf目录下的zoo_sample.cfg改名成zoo.cfg,这里我是先备份了zoo_sample.cfg再改的名。修改zoo.cfg的值如下
# The number of milliseconds of each tick

tickTime=2000

# The number of ticks that the initial

# synchronization phase can take

initLimit=10

# The number of ticks that can pass between

# sending a request and getting an acknowledgement

syncLimit=5

# the directory where the snapshot is stored.

# do not use /tmp for storage, /tmp here is just

# example sakes.

dataDir=D:/zookeeper-3.4.9/data/data

dataLogDir=D:/zookeeper-3.4.9/data/log

# the port at which the clients will connect

clientPort=2181

# the maximum number of client connections.

# increase this if you need to handle more clients

#maxClientCnxns=60

#

# Be sure to read the maintenance section of the

# administrator guide before turning on autopurge.

# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance

# The number of snapshots to retain in dataDir

#autopurge.snapRetainCount=3

# Purge task interval in hours

# Set to "0" to disable auto purge feature

#autopurge.purgeInterval=1
  1. 配置Zookeeper环境变量

我们再配置一下这个环境变量就可以运行zookeeper了。(本文基于Windows已经配置过JAVA_HOME并且配置正确)

新增环境变量:ZOOKEEPER_HOME   值:D:/zookeeper-3.4.9(根据你的主目录设置)

新增Path: ;%ZOOKEEPER_HOME%/bin; %ZOOKEEPER_HOME%/conf

 

③ 启动Zookeeper服务

点击bin目录下的zkServer.cmd 这时候出现下面的提示就说明配置成功了。

注意 :这个窗口不要关闭!让注册中心服务一直运行。

​​​​​​​测试Zookeeper注册中心

按照之前的步骤,先启动服务提供者,再启动服务消费者。​​​​​​​

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值