dubbo 集群容错模式源码学习---ForkingCluster
2018-10-30 19:30
393 查看
ForkingCluster 模式
思想:服务端多个节点并行响应(并发任务)某个服务的请求,将执行完的结果放在一个阻塞队列中(FIFO)。第一个完成的任务的结果进入队列,将会马上返回,不会等待所有任务执行完成, 只要有一个任务完成,结果放到队列中,队列中弹出第一个(最快完成响应的那个节点)结果, 返回服务请求方。如果n 个并发任务都出错了,抛异常,将最后一个异常放到队列中。服务请求返回就是抛异常。通常用于实时性高的读操作,相对耗费资源。最大并行数要可配置。
public class ForkCluster { private final ExecutorService executor = Executors.newCachedThreadPool(); @Test public void run() { String response = forkCluster(); System.out.println(response); } /** * 思想:多个节点并行响应(并发任务)某个服务的请求,将执行完的结果放在一个阻塞队列中(FIFO)。 * 不会等待所有任务执行完成, 只要有一个任务完成,结果放到队列中,队列中弹出第一个(最快完成响应的那个节点)结果, 返回服务请求方。 * 如果n 个并发任务都出错了,抛异常,将最后一个异常放到队列中。服务请求返回就是抛异常。 * * 通常用于实时性高的读操作,相对耗费资源。最大并行数要可配置。 * * */ public String forkCluster() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); List<Node> cluster = new ArrayList<>(); cluster.add(node1); cluster.add(node2); cluster.add(node3); cluster.add(node4); BlockingQueue<Object> responses = new LinkedBlockingQueue<>(); final AtomicInteger count = new AtomicInteger(); // 统计异常节点的个数. for (Node node : cluster) { executor.execute(new Runnable() { @Override public void run() { try { String response = node.doSomething(); responses.offer(response); }catch (Throwable e) { int value = count.incrementAndGet(); if (value >= cluster.size()) responses.offer(e); } } }); } try { Object resp = responses.poll(1000, TimeUnit.MILLISECONDS); if (resp instanceof Throwable) { throw new RuntimeException("Cannot perform cluster fork. "); } return (String)resp; } catch (InterruptedException e) { throw new RuntimeException("Cannot get cluster fork response."); } } class Node { private int id; Node(int id) { this.id = id; } String doSomething() { return "Node " + id + "第一个完成响应"; }; }
}
阅读更多相关文章推荐
- dubbo 集群容错模式源码学习 -- FaibackCluster
- dubbo 学习(4) 集群容错模式和负载均衡模式
- spark源码学习(六):standalone模式的cluster集群源码解读
- Dubbo 源码分析 - 集群容错之 Router
- 结合redis设计与实现的redis源码学习-22-集群(cluster.c)
- Dubbo -- 系统学习 笔记 -- 示例 -- 集群容错
- dubbo集群容错模式
- Java for Web学习笔记(九二):消息和集群(7)RabbitMQ和消息模式(上)
- 14. Dubbo原理解析-集群&容错之Cluster
- Dubbo中集群Cluster,负载均衡,容错,路由解析
- 2 dubbo源码之集群容错实现
- dubbo 源码学习笔记 (六) —— 集群模块
- Dubbo源码学习--集群负载均衡算法的实现
- dubbo源码解析-集群容错架构设计
- dubbo源码解析-集群容错架构设计
- Dubbo学习(四):集群容错
- Driver在Cluster模式下的启动、两种不同的资源调度方式源码彻底解析、资源调度内幕总结
- activemq-集群和主从模式 学习笔记
- dubbo 源码学习笔记 (一) —— ExtensionLoader和URL
- Apache Spark源码走读之19 -- standalone cluster模式下资源的申请与释放