为hazelcast配置atomikos

时间:2016-03-08 06:07:09

标签: hazelcast

我如何为HazelCast实例配置Atomikos。按照mastering-hazel强制转换,我们只能在java中进行。如何配置就像我为数据库做的那样。如果配置是java的方式,那我怎么做使用TransactionalTask​​删除样板代码开始并提交transactions.i尝试过像

public void insertIntoGridJTA( final List<String> list)
            throws NotSupportedException, SystemException,
            IllegalStateException, RollbackException {
        HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
        HazelcastXAResource xaResource = hazelcast.getXAResource();
        TransactionContext context = xaResource.getTransactionContext();
        hazelcast.executeTransaction(new  TransactionalTask<Object>() {
        public Object execute(TransactionalTaskContext context)
                    throws TransactionException {
                // TODO Auto-generated method stub
            TransactionalMap<Integer, String> map = context.getMap("demo");
            System.out.println("map"+map.getName());
            for (int i = 0; i < list.size(); i++) {
                map.put(i, list.get(i));
            }
                return null;
        }
        });
    }

但如果我正在使用TransactionalTask​​

,则交易无法启动

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

除了@noctarius,我过去也是这样做的

@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private HazelcastXAResource hzXAResource;
@Autowired
private UserTransactionManager userTransactionManager;

@Transactional
public void insert() throws SystemException, RollbackException {
    final Transaction transaction = userTransactionManager.getTransaction();
    transaction.enlistResource(hzXAResource);
    final TransactionContext hzTransactionContext = hzXAResource.getTransactionContext();
    final TransactionalMap<Long, String> hzCustomerMap = hzTransactionContext.getMap("hzCustomerMap");

    // Use a Java 8 stream to print out each tuple of the list
    CUSTOMERS_TEST_DATA.forEach(customer -> {
        log.info("Inserting customer record for {}", customer);
        hzCustomerMap.put(customer.getId(), customer.toString());
    });
    jdbcTemplate.batchUpdate(Sql.SQL_INSERT.getSql(), new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, CUSTOMERS_TEST_DATA.get(i).getFirstName());
            ps.setString(2, CUSTOMERS_TEST_DATA.get(i).getLastName());
        }

        @Override
        public int getBatchSize() {
            return CUSTOMERS_TEST_DATA.size();
        }
    });

    // Uncomment this to test the failure of the transaction
    //        hzCustomerMap.values((Predicate) entry -> {
    //            throw new RuntimeException();
    //        });

    transaction.delistResource(hzXAResource, XAResource.TMSUCCESS);
}