1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.allanbank.mongodb.client.state;
21
22 import java.io.IOException;
23 import java.util.List;
24
25 import com.allanbank.mongodb.client.connection.Connection;
26 import com.allanbank.mongodb.util.IOUtils;
27 import com.allanbank.mongodb.util.log.Log;
28 import com.allanbank.mongodb.util.log.LogFactory;
29
30
31
32
33
34
35
36
37
38 public class SimpleReconnectStrategy extends AbstractReconnectStrategy {
39
40
41 protected static final Log LOG = LogFactory
42 .getLog(SimpleReconnectStrategy.class);
43
44
45
46
47 public SimpleReconnectStrategy() {
48 super();
49 }
50
51
52
53
54
55
56
57
58 @Override
59 public Connection reconnect(final Connection oldConnection) {
60
61
62 final boolean wasInterrupted = Thread.interrupted();
63 try {
64
65
66 final Server origServer = myState
67 .get(oldConnection.getServerName());
68 Connection newConn = tryConnect(origServer);
69 if (newConn != null) {
70 return newConn;
71 }
72
73 final List<Server> servers = getSelector().pickServers();
74 for (final Server server : servers) {
75 newConn = tryConnect(server);
76 if (newConn != null) {
77 return newConn;
78 }
79 }
80
81 LOG.info("Reconnect attempt failed for all {} servers: {}",
82 servers.size(), servers);
83 }
84 finally {
85
86 if (wasInterrupted) {
87 Thread.currentThread().interrupt();
88 }
89 }
90
91 return null;
92 }
93
94
95
96
97
98
99
100
101 private Connection tryConnect(final Server server) {
102 Connection newConn = null;
103 try {
104
105 newConn = getConnectionFactory().connect(server, getConfig());
106 if (isConnected(server, newConn)) {
107 LOG.info("Reconnected to {}", server);
108
109
110 final Connection result = newConn;
111 newConn = null;
112
113 return result;
114 }
115 }
116 catch (final IOException error) {
117
118 LOG.debug("Reconnect to {} failed: {}", server, error.getMessage());
119 }
120 finally {
121 IOUtils.close(newConn);
122 }
123 return null;
124 }
125 }