I have a Hazelcast
in my project, which works on two members in a cluster. Simultaneously, I use Hazelcast's IScheduledExecutorService
to schedule a task, which gets some data form DB and put it in a cache at fixed rate.
The problem is, that my task class (task for that scheduler) has some fields, that couldn't be serialized (IScheduledExecutorService
trying to do it), such as mybatis Mappers and hazelcast's CacheManager, which get and put data from DB to cache.
I tried to use Spring's features, such as @Autowire
on that fields and @SpringAware
on class, but no luck.
May be there is some Hazelcast or Spring feature which I don't know? Any help would be appreciated.
my task class:
@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);
}
}
my scheduler:
@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);
}
}
}
@SpringAware is disabled by default. (See this issue why it was disabled) You need to enable it by declaring <hz:spring-aware />
or programmatically like in this example.