Hazelcast锁定不提供同步

时间:2018-09-18 12:12:06

标签: java spring hazelcast

我正在尝试在Hazelcast中实现方法同步,但是即使在单个群集上,它似乎也不起作用。

我正在使用一个简单的Hazelcast配置

@Configuration
public class HazelcastConfig {
    @Bean
    HazelcastInstance hazelcastInstance(){
        return Hazelcast.newHazelcastInstance();
    }
}

有一个示例服务,它使用时间戳生成一些ID。它应该是唯一的,所以我正在使用Hazelcast提供的锁

@Service
public class MyService {
    @Autowired
    private HazelcastInstance hazelcastInstance;

    public Long generateVersion(){
        ILock lock = hazelcastInstance.getLock("version_key");
        try{
            lock.lock();
            return System.currentTimeMillis();
        } catch (Exception ex) {
            LOGGER.error("Could not generate version ", ex);
            throw ex;
        } finally{
            lock.unlock();
        }
    }
}

进行测试检查,确认没有重复生成。

@Test
public void test() throws InterruptedException, ExecutionException {
    List<Long> versions = new ArrayList();
    Collection<Callable<Long>> tasks = new ArrayList<>();
    int nThreads = 100;
    for(int i=0; i<nThreads; i++){
        tasks.add(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                return myService.generateVersion();
            }
        });
    }
    ExecutorService executor = Executors.newFixedThreadPool(nThreads);
    List<Future<Long>> results = executor.invokeAll(tasks);
    for(Future<Long> result : results){
        Long pingResult = result.get();
        if (!versions.contains(pingResult))
            versions.add(pingResult);
        else
            throw new AssertionError("Found duplicate "+ pingResult);
    }
}

但是,在运行测试时,我得到了很多重复。测试在单个节点上运行(我计划以后在集群环境中运行)。

hazelcast是否在单个群集节点上提供同步?还是我配置错误?

1 个答案:

答案 0 :(得分:1)

private final String AES_MODE = "AES/CBC/PKCS7Padding"; private byte[] Encryption(final SecretKeySpec key, final byte[] iv, final byte[] message) throws GeneralSecurityException { final Cipher cipher = Cipher.getInstance(AES_MODE); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = cipher.doFinal(message); return cipherText; } 可能不是唯一的。您可以两次调用它并获得相同的结果。

您可以让Hazelcast为您生成https://docs.hazelcast.org//docs/3.10.5/javadoc/com/hazelcast/flakeidgen/FlakeIdGenerator.html

的ID