首页 > 解决方案 > Hazelcast 的 IScheduledExecutorService 无法序列化任务

问题描述

我的项目中有一个Hazelcast,它适用于集群中的两个成员。同时,我使用 HazelcastIScheduledExecutorService来安排一个任务,该任务从 DB 中获取一些数据并以固定速率将其放入缓存中。

问题是,我的任务类(该调度程序的任务)有一些字段,无法序列化(IScheduledExecutorService尝试这样做),例如 mybatis Mappers 和 hazelcast 的 CacheManager,它们从数据库获取数据并将数据放入缓存。

我尝试使用 Spring 的功能,例如@Autowire在该字段和@SpringAware课堂上,但没有运气。

可能有一些我不知道的 Hazelcast 或 Spring 功能?任何帮助,将不胜感激。

我的任务课:

@Service
@SpringAware
public class MyTask implements Runnable, Serializable {

private static final Logger LOG = LoggerFactory.getLogger(MyTask.class);

private static final String CACHE1 = "cache1";
private static final String CACHE2 = "cache2";
private static final String KEY1 = "key1";
private static final String KEY2 = "key2";

@Autowired
private MapperOne mapperOne;

@Autowired
private MapperTwo mapperTwo;

@Autowired
// if mark it 'transient' it would be null for other threads
private transient CacheManager cacheManager;

@Override
public void run() {
    LOG.info("ABOUT TO UPDATE CACHE");
    List<SomeStuff> stuff1 = mapperOne.getData();
    List<OtherStuff> stuff2 = mapperTwo.getData();

    cacheManager.getCache(CACHE1).put(KEY1, stuff1);
    cacheManager.getCache(CACHE2).put(KEY2, stuff2);
}

}

我的调度程序:

@Service
public class MySchedulerService {

@Autowired
private MyTask myTask;

@PostConstruct
void init() {
    if (hazelcastInstance.getCluster().getMembers().iterator().next().localMember()) {
        IScheduledExecutorService notificationCacheService =
            hazelcastInstance.getScheduledExecutorService("myService");
        notificationCacheService.scheduleOnKeyOwnerAtFixedRate(
            myTask, hazelcastInstance.getCluster().getLocalMember(), 0, 15, TimeUnit.SECONDS);
    }
}

}

标签: javaspringserializationscheduled-taskshazelcast

解决方案


@SpringAware 默认禁用。(请参阅这个问题为什么它被禁用)您需要通过声明<hz:spring-aware />或以编程方式启用它,就像在这个示例中一样。


推荐阅读