Dubbo源码分析系列1:范例

本文通过实战演示了如何使用 Dubbo 框架搭建简单的RPC服务。包括客户端和服务端的代码实现,配置文件解析,以及如何利用Zookeeper进行服务注册与发现。

下面,我们开始写一个小例子。

找到1个例子:https://my.oschina.net/penngo/blog/495613

按照这篇文章,撸了1个小工程。可以顺利运行。那就开始debug源码。

===其中,有pom.xml报错,找不到namespace的问题,见

http://blog.youkuaiyun.com/happylife_haha/article/details/52755425

==================================================

server端

jdb com.penngo.dubbo.server.Server
stop in com.penngo.dubbo.server.Server.main

stop in org.springframework.context.support.AbstractApplicationContext.refresh

stop in org.springframework.context.support.AbstractApplicationContext.prepareRefresh

run

首先,先进行xml解析

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "dubbo-penngo-provider.xml" });

先看zk的数据

[zk: localhost:2181(CONNECTED) 5] ls /dubbo
[com.penngo.dubbo.service.RegisterService, com.penngo.dubbo.service.LoginService]

看来dubbo把全部的consumer和provider都做了保存。

 

 

下面附上全部代码

package com.penngo.dubbo.client;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.penngo.dubbo.service.LoginService;
import com.penngo.dubbo.service.RegisterService;
import com.penngo.dubbo.service.User;

public class Client {
	public static void main(String[] args) throws Exception {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "dubbo-penngo-consumer.xml" });
		context.start();

		LoginService loginService = (LoginService) context.getBean("loginService"); // 获取远程服务代理
		User user = loginService.login("penngo", "123");

		System.out.println("*****************"+user.getId() + " " + user.getName()); // 显示调用结果

		RegisterService registerService = (RegisterService) context.getBean("registerService");
		User user2 = registerService.createUser("penngo", "123");
		System.out.println("*****************"+user2.getId() + " " + user2.getName()); // 显示调用结果
		while(true){
			Thread.currentThread().sleep(10000000);
		}
	}
}
package com.penngo.dubbo.server;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Server {
	public static void main(String[] args) throws Exception {
		// 看到这里了
		// 看到这里了
		// 看到这里了
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "dubbo-penngo-provider.xml" });
		context.start();
		System.in.read(); // 按任意键退出
	}
}
package com.penngo.dubbo.service;

public interface LoginService {
	public User login(String name, String psw);

}
package com.penngo.dubbo.service;

public interface RegisterService {
	public User createUser(String name, String psw);
}
package com.penngo.dubbo.service;

import java.util.Arrays;
import java.util.List;

/**
 * User
 * 
 * @author william.liangf
 */
public class User implements java.io.Serializable {

	private static final long serialVersionUID = 7330539198581235339L;

	public static final String REALM = "dubbo";

	public static final String ROOT = "R";

	public static final String ADMINISTRATOR = "A";

	public static final String MANAGER = "M";

	public static final String GUEST = "G";

	public static final String ANONYMOUS = "anonymous";

	public static final String LEGACY = "legacy";
	private long id;
	private String username;

	private String password;

	private String role;

	private String creator;

	private boolean enabled;

	private String name;

	private String department;

	private String email;

	private String phone;

	private String alitalk;

	private String locale;

	private String servicePrivilege;

	private List<String> servicePrivileges;

	public User() {
	}

	public User(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 String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public boolean hasServicePrivilege(String[] services) {
		if (services == null || services.length == 0)
			throw new IllegalArgumentException("services == null");
		for (String service : services) {
			boolean r = hasServicePrivilege(service);
			if (!r)
				return false;
		}
		return true;
	}

	public static boolean isValidPrivilege(String servicePrivilege) {
		if (servicePrivilege == null || servicePrivilege.length() == 0) {
			return true;
		}
		String[] privileges = servicePrivilege.trim().split("\\s*,\\s*");
		for (String privilege : privileges) {
			if (privilege.endsWith("*")) {
				privilege = privilege.substring(0, privilege.length() - 1);
			}
			if (privilege.indexOf('*') > -1) {
				return false;
			}
		}
		return true;
	}

	public boolean canGrantPrivilege(String servicePrivilege) {
		if (servicePrivilege == null || servicePrivilege.length() == 0) {
			return true;
		}
		if (servicePrivileges == null || servicePrivileges.size() == 0) {
			return false;
		}
		String[] privileges = servicePrivilege.trim().split("\\s*,\\s*");
		for (String privilege : privileges) {
			boolean hasPrivilege = false;
			for (String ownPrivilege : servicePrivileges) {
				if (matchPrivilege(ownPrivilege, privilege)) {
					hasPrivilege = true;
				}
			}
			if (!hasPrivilege) {
				return false;
			}
		}
		return true;
	}

	private boolean matchPrivilege(String ownPrivilege, String privilege) {
		if ("*".equals(ownPrivilege) || ownPrivilege.equals(privilege)) {
			return true;
		}
		if (privilege.endsWith("*")) {
			if (!ownPrivilege.endsWith("*")) {
				return false;
			}
			privilege = privilege.substring(0, privilege.length() - 1);
			ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1);
			return privilege.startsWith(ownPrivilege);
		} else {
			if (ownPrivilege.endsWith("*")) {
				ownPrivilege = ownPrivilege.substring(0, ownPrivilege.length() - 1);
			}
			return privilege.startsWith(ownPrivilege);
		}
	}

	public boolean hasServicePrivilege(String service) {
		if (service == null || service.length() == 0)
			return false;
		if (role == null || GUEST.equalsIgnoreCase(role)) {
			return false;
		}
		if (ROOT.equalsIgnoreCase(role)) {
			return true;
		}

		if (servicePrivileges != null && servicePrivileges.size() > 0) {
			for (String privilege : servicePrivileges) {
				boolean ok = true;// ParseUtils.isMatchGlobPattern(privilege,service);
				if (ok) {
					return true;
				}
			}
		}
		return false;
	}

	public String getServicePrivilege() {
		return servicePrivilege;
	}

	public void setServicePrivilege(String servicePrivilege) {
		this.servicePrivilege = servicePrivilege;
		if (servicePrivilege != null && servicePrivilege.length() > 0) {
			servicePrivileges = Arrays.asList(servicePrivilege.trim().split("\\s*,\\s*"));
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getAlitalk() {
		return alitalk;
	}

	public void setAlitalk(String alitalk) {
		this.alitalk = alitalk;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public String getLocale() {
		return locale;
	}

	public void setLocale(String locale) {
		this.locale = locale;
	}

	public long getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}
package com.penngo.dubbo.serviceimpl;
import com.penngo.dubbo.service.LoginService;
import com.penngo.dubbo.service.User;

public class LoginServiceImpl implements LoginService{
	public LoginServiceImpl(){
		new Exception().printStackTrace();
	}
	public User login(String name, String psw){
        User user = null;
        if(name.equals("penngo") && psw.equals("123")){
            user = new User();
            user.setId(1);
            user.setName("penngo");
        }
        return user;
    }
}
package com.penngo.dubbo.serviceimpl;

import com.penngo.dubbo.service.RegisterService;
import com.penngo.dubbo.service.User;

public class RegisterServiceImpl implements RegisterService {
	public User createUser(String name, String psw) {
		User user = new User();
		user.setId(2);
		user.setName(name);
		user.setPassword(psw);
		return user;
	}
}
<?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="consumer-penngo-app"  />

    <dubbo:registry address="zookeeper://106.14.92.192:2181" />
    <!-- 使用multicast广播注册中心暴露发现服务地址 -->
    <!--   <dubbo:registry address="multicast://224.5.6.7:1234" />  -->
    
    <!-- 生成远程服务代理, -->
	<dubbo:reference id="loginService" interface="com.penngo.dubbo.service.LoginService" />
	<dubbo:reference id="registerService" interface="com.penngo.dubbo.service.RegisterService" />
</beans>
<?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="provider-penngo-app" />

	<!-- 使用zookeeper广播注册中心暴露服务地址 -->
	<dubbo:registry address="zookeeper://106.14.92.192:2181" />
	<!-- <dubbo:registry address="multicast://224.5.6.7:1234" /> -->

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

	<!-- 和本地bean一样实现服务 -->
	<bean id="loginService" class="com.penngo.dubbo.serviceimpl.LoginServiceImpl" />
	<bean id="registerService" class="com.penngo.dubbo.serviceimpl.RegisterServiceImpl" />

	<!-- 声明需要暴露的服务接口 -->
	<dubbo:service interface="com.penngo.dubbo.service.LoginService"
		ref="loginService" />
	<dubbo:service interface="com.penngo.dubbo.service.RegisterService"
		ref="registerService" />

</beans>
log4j.rootLogger=DEBUG,stdout
log4j.logger.org=DEBUG,stdout
log4j.logger.com.freedom.mysql.myrwsplit=INFO
log4j.logger.org.apache.ibatis=INFO
log4j.logger.com.alibaba.druid=INFO
log4j.logger.org.apache.zookeeper=INFO
log4j.logger.org.springframework=INFO
log4j.logger.com.alibaba.dubbo=INFO

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.file=${workDir}
log4j.appender.logfile.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d [%-5p] %m - [%c.%L] %n




log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %m - [%c.%L] %n
<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>
	<parent>
		<groupId>com.alibaba</groupId>
		<artifactId>dubbo-parent</artifactId>
		<version>2.5.4-SNAPSHOT</version>
	</parent>
	<artifactId>my_test</artifactId>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.0.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>2.5.4-SNAPSHOT</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo-remoting-zookeeper</artifactId>
			<version>2.5.4-SNAPSHOT</version>
		</dependency>

	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<excludes>

				</excludes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<mainClass></mainClass>
						</manifest>
					</archive>
					<excludes>
						<exclude>**/*.xml</exclude>
						<exclude>**/*.properties</exclude>
						<exclude>**/*.thrift</exclude>
					</excludes>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass></mainClass>
						</manifest>
						<manifestEntries>
							<Class-Path>.</Class-Path>
						</manifestEntries>
					</archive>
					<excludes>
						<exclude>**/*.xml</exclude>
						<exclude>**/*.properties</exclude>
						<exclude>**/*.thrift</exclude>
					</excludes>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

转载于:https://my.oschina.net/qiangzigege/blog/920031

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值