解决OSCache集群情况下缓存不同步的问题

问题描述:oscache集群环境下,如果网络发生故障,会导致集群变成多个小的子群甚至单节点,这期间如果其中一节点做了更新缓存的操作,当网络恢复后,集群中的cache状态会不一致,导致用户看到不同的view。
解决思路:获取网络恢复后子群合并时产生的通知,并进行更新。最简单有效的就是清空所有节点的缓存。
jar版本:oscache2.4.1 jgroups2.12.1

oscache在集群环境下的配置需要打开cache.event.listeners属性,里面包含JavaGroupsBroadcastingListener。
JavaGroupsBroadcastingListener使用了JGroups的NotificationBus进行通信,而NotificationBus实现了receiver接口,其中的ViewAccept就是在view变化时被调用的。
我们需要做的是重写JavaGroupsBroadcastingListener的初始化方法。
重写NotificationBus的viewAccept方法。
修改oscache.properties里面的cache.event.listeners.
红色是添加或修改的,上代码:

MySelfJavaGroupsBroadcastingListener类:

    public synchronized void initialize(Cache cache, Config config) throws InitializationException {
        super.initialize(cache, config);

        String properties = config.getProperty(CHANNEL_PROPERTIES);
        String multicastIP = config.getProperty(MULTICAST_IP_PROPERTY);

        if ((properties == null) && (multicastIP == null)) {
            multicastIP = DEFAULT_MULTICAST_IP;
        }

        if (properties == null) {
            properties = DEFAULT_CHANNEL_PROPERTIES_PRE + multicastIP.trim() + DEFAULT_CHANNEL_PROPERTIES_POST;
        } else {
            properties = properties.trim();
        }

        if (log.isInfoEnabled()) {
            log.info("Starting a new JavaGroups broadcasting listener with properties=" + properties);
        }

        try {
            bus = new MySelfNotificationBus(BUS_NAME, properties);            bus.start();
            bus.getChannel().setOpt(Channel.LOCAL, new Boolean(false));
            bus.setConsumer(this);
            log.info("JavaGroups clustering support started successfully");
        } catch (Exception e) {
            throw new InitializationException("Initialization failed: " + e);
        }
    }



MySelfNotificationBus类:

public class MySelfNotificationBus extends NotificationBus {

    public MySelfNotificationBus (String bus_name, String properties) throws Exception {
    super(bus_name,properties);
    }
   
    public synchronized void viewAccepted(View new_view) {
    super.viewAccepted(new_view);
    final NotificationBus bus = this;
    if(new_view instanceof MergeView){
    new Thread() {
                public void run() {
                bus.notifyConsumer(new ClusterNotification(ClusterNotification.FLUSH_CACHE,new Date()));
                }
            }.start();
    }
    }


oscache.properties:

cache.event.listeners= x.x.x.MySelfJavaGroupsBroadcastingListener,  \
                      com.opensymphony.oscache.extra.CacheEntryEventListenerImpl,               \
                      com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl,           \
                      com.opensymphony.oscache.extra.ScopeEventListenerImpl

你可能感兴趣的:(Java综合)