向注册中心写入路由规则:(通常由监控中心或治理中心的页面完成)
RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(URL.valueOf("zookeeper://10.20.153.10:2181"));
registry.register(URL.valueOf("condition://0.0.0.0/com.foo.BarService?category=routers&dynamic=false&rule=" + URL.encode("http://10.20.160.198/wiki/display/dubbo/host = 10.20.153.10 => host = 10.20.153.11") + "));
其中:
基于条件表达式的路由规则,如:host = 10.20.153.10 => host = 10.20.153.11
规则:
表达式:
=
表示"匹配",如:host = 10.20.153.10!=
表示"不匹配",如:host != 10.20.153.10,
分隔多个值,如:host != 10.20.153.10,10.20.153.11*
结尾,表示通配,如:host != 10.20.*$
开头,表示引用消费者参数,如:host = $host示例:
排除预发布机:
=> host != 172.22.3.91
白名单: 注意:一个服务只能有一条白名单规则,否则两条规则交叉,就都被筛选掉了)
host != 10.20.153.10,10.20.153.11 =>
黑名单:
host = 10.20.153.10,10.20.153.11 =>
服务寄宿在应用上,只暴露一部分的机器,防止整个集群挂掉:
=> host = 172.22.3.1*,172.22.3.2*
为重要应用提供额外的机器:
application != kylin => host != 172.22.3.95,172.22.3.96
读写分离:
method = find*,list*,get*,is* => host = 172.22.3.94,172.22.3.95,172.22.3.96
method != find*,list*,get*,is* => host = 172.22.3.97,172.22.3.98
前后台分离:
application = bops => host = 172.22.3.91,172.22.3.92,172.22.3.93
application != bops => host = 172.22.3.94,172.22.3.95,172.22.3.96
隔离不同机房网段:
host != 172.22.3.* => host != 172.22.3.*
提供者与消费者部署在同集群内,本机只访问本机的服务:
=> host = $host
支持JDK脚本引擎的所有脚本,比如:javascript, jruby, groovy 等,通过 type=javascript 参数设置脚本类型,缺省为javascript。
脚本没有沙箱约束,可执行任意代码,存在后门风险
"script://0.0.0.0/com.foo.BarService?category=routers&dynamic=false&rule=" + URL.encode("function route(invokers) { ... } (invokers)")
基于脚本引擎的路由规则,如:
function route(invokers) {
var result = new java.util.ArrayList(invokers.size());
for (i = 0; i < invokers.size(); i ++) {
if ("http://10.20.160.198/wiki/display/dubbo/10.20.153.10".equals(invokers.get(i).getUrl().getHost())) {
result.add(invokers.get(i));
}
}
return result;
} (invokers); // 表示立即执行方法
原文:http://www.cnblogs.com/jmbkeyes/p/7542729.html