View Javadoc
1   package com.atlassian.cache.ehcache.cluster;
2   
3   import java.util.Date;
4   import java.util.List;
5   import java.util.Properties;
6   
7   import com.google.common.collect.ImmutableList;
8   
9   import net.sf.ehcache.CacheException;
10  import net.sf.ehcache.CacheManager;
11  import net.sf.ehcache.Ehcache;
12  import net.sf.ehcache.distribution.CachePeer;
13  import net.sf.ehcache.distribution.RMICacheManagerPeerProvider;
14  
15  import static com.atlassian.cache.ehcache.cluster.EhCacheConfigurationFactory.BASE_PORT;
16  import static com.atlassian.cache.ehcache.cluster.EhCacheConfigurationFactory.LOCALHOST;
17  
18  /**
19   * @since v2.4.5
20   */
21  public class EhCachePeerProvider extends RMICacheManagerPeerProvider
22  {
23      static final String THIS_NODE_ID = "thisNodeId";
24      static final String MAX_NODE_ID = "maxNodeId";
25  
26      private final int thisNodeId;
27      private final int maxNodeId;
28  
29      public EhCachePeerProvider(CacheManager cacheManager, Properties properties)
30      {
31          super(cacheManager);
32          this.thisNodeId = Integer.parseInt(properties.getProperty(THIS_NODE_ID));
33          this.maxNodeId = Integer.parseInt(properties.getProperty(MAX_NODE_ID));
34      }
35  
36      @Override
37      public void init()
38      {
39      }
40  
41      @Override
42      public long getTimeForClusterToForm()
43      {
44          return 0;
45      }
46  
47      @Override
48      public final void registerPeer(String rmiUrl)
49      {
50          //Nothing to do here
51      }
52  
53      @Override
54      public List<CachePeer> listRemoteCachePeers(Ehcache cache) throws CacheException
55      {
56          final ImmutableList.Builder<CachePeer> list = ImmutableList.builder();
57          for (int otherNodeId = 1; otherNodeId <= maxNodeId; ++otherNodeId)
58          {
59              if (thisNodeId != otherNodeId)
60              {
61                  try
62                  {
63                      final String rmiUrl = buildBaseUrl(otherNodeId, cache.getName());
64                      list.add(lookupRemoteCachePeer(rmiUrl));
65                  }
66                  catch (Exception e)
67                  {
68                      System.err.println("No binding from node" + thisNodeId + " to node" + otherNodeId +
69                              " for cache '" + cache.getName() + '\'');
70                  }
71              }
72          }
73          return list.build();
74      }
75  
76      @Override
77      protected boolean stale(Date date)
78      {
79          return false;
80      }
81  
82      private static String buildBaseUrl(final int otherNodeId, final String cacheName)
83      {
84          final int port = BASE_PORT + otherNodeId;
85          return "//" + LOCALHOST + ':' + port + '/' + cacheName;
86      }
87  
88  }