Java Code Examples for com.hazelcast.core.IMap#remove()

The following examples show how to use com.hazelcast.core.IMap#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OrderData.java    From match-trade with Apache License 2.0 6 votes vote down vote up
/**
 * @Title: new_order
 * @Description: TODO(接收撤销订单数据)
 * @param  参数
 * @return void 返回类型
 * @throws
 */
@KafkaListener(id = "cancel_order", topics = "cancel_order")
public void cancel_order(String param) {
	log.info("===收到cancel_order:"+param);
	CancelOrderParam cancel = JSON.parseObject(param, CancelOrderParam.class);
	IMap<Long, MatchOrder> order_map = hzInstance.getMap(HazelcastUtil.getOrderBookKey(cancel.getCoinTeam(), cancel.getIsBuy()));
	if (order_map.containsKey(cancel.getId())) {
		TransactionOptions options = new TransactionOptions().setTransactionType(TransactionOptions.TransactionType.ONE_PHASE);
		TransactionContext context = hzInstance.newTransactionContext(options);
		context.beginTransaction();
		try {
			IMap<BigDecimal, BigDecimal> map = hzInstance.getMap(HazelcastUtil.getMatchKey(cancel.getCoinTeam(), cancel.getIsBuy()));
			MatchOrder cmo = order_map.remove(cancel.getId());
			map.compute(cmo.getPrice(), (k,v) -> v.subtract(cmo.getUnFinishNumber()));
			if (map.get(cmo.getPrice()).compareTo(BigDecimal.ZERO) >-1) {
				context.commitTransaction();
				pushData.updateOrder(cmo); //推送撤销成功结果
			}else {
				throw new Exception();
			}
		} catch (Exception e) {
			context.rollbackTransaction();
		}
	}
}
 
Example 2
Source File: HazelcastTransactionManager.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
protected void unlock(TransactionDefinition definition) {
    Instant now = Instant.now();
    String name = definition.getName();
    final IMap<String, HazelcastTransactionDefinition> store = getStore();
    try {
        store.lock(name);
        HazelcastTransactionDefinition current = store.get(name);
        if (current == null) {
            throw new TransactionUnlockException();
        } else if (now.isAfter(current.getMost())) {
            throw new TransactionUnlockException();
        } else {
            store.remove(name);
        }
    } finally {
        store.unlock(name);
    }
}
 
Example 3
Source File: ListenerDemo.java    From hazelcast-demo with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> map = ins.getMap("");
	map.addEntryListener(new ListenerExample(), true);//添加自定义监听器
	map.put(1, "Grand Theft Auto");
	map.put(1, "Final Fantasy");
	map.put(2, "World Of Warcraft");
	
	HazelcastInstance insex = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> mapex = insex.getMap("");
	
	System.out.println(mapex.get(1));
	System.out.println(mapex.get(2));
	mapex.remove(1);
	mapex.remove(2);
	System.exit(0);
}
 
Example 4
Source File: InterceptorDemo.java    From hazelcast-demo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> imap = ins.getMap("");
	imap.addInterceptor(new InterceptorExample());// 添加拦截器
	imap.put(1, "Mei");
	imap.put(1, "Tracer");
	imap.put(1, "D.va");
	imap.put(1, "Mercy");
	
	imap.get(1);
	imap.remove(1);
	System.out.println(imap.get(1));
}
 
Example 5
Source File: SubscriptionMain.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args){
    Config config = new Config();
    GlobalSerializerConfig globalConfig = new GlobalSerializerConfig();
    globalConfig.setOverrideJavaSerialization(true).setImplementation(new DataSerializer());

    config.getSerializationConfig().setGlobalSerializerConfig(globalConfig);

   HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);

   IMap<String, String> aMap = instance.getMap("aMap");

   aMap.addEntryListener(new MyListener(), true);

   
   aMap.put("key", "value");
   aMap.put("key", "Another value");
   aMap.remove("key");
   aMap.put("other key", "other value");
   aMap.clear();


   IMap<String, Data> otherMap = instance.getMap("otherMap");

   otherMap.addEntryListener(new MyListener(), true);
   otherMap.put("key", new Data());
   Data data = otherMap.get("key");
   data.date=new Date();
   data.value=1000;
   otherMap.put("key",data);

   instance.shutdown();
}
 
Example 6
Source File: MatchExecutor.java    From match-trade with Apache License 2.0 4 votes vote down vote up
public MatchOrder doMatch(MatchOrder input) {
	try {
		// 获取对手盘口
		IMap<BigDecimal, BigDecimal> outMap = hzInstance.getMap(HazelcastUtil.getMatchKey(input.getCoinTeam(), !input.getIsBuy()));
		if (null!=outMap&&outMap.size()>0) {
			BigDecimal outPrice = HazelcastUtil.getOptimalMatch(outMap,input.getIsBuy()); 
			if (HazelcastUtil.canMatch(input, outPrice)) {
				BigDecimal outNum = outMap.get(outPrice);
				if (outNum.compareTo(BigDecimal.ZERO)<1) {
					outMap.remove(outPrice);
					doMatch(input); // 递归处理
				}
				int contrast = input.getUnFinishNumber().compareTo(outNum);
				BigDecimal dealNum = contrast > -1?outNum:input.getUnFinishNumber();
				input.setFinishNumber(input.getFinishNumber().add(dealNum));
				input.setUnFinishNumber(input.getUnFinishNumber().subtract(dealNum));
				if (input.getIsBuy()) {
					input.setSurplusFrozen(input.getSurplusFrozen().subtract(outPrice.multiply(dealNum)));
				}else {
					input.setSurplusFrozen(input.getSurplusFrozen().subtract(dealNum));
				}
				//撮合详情记录 >>> 一个价格一个详情
				matchDetailHandler.sendTradeRecord(input, outPrice, dealNum, DealWay.TAKER);
				List<LevelMatch> lms = input.getList();
				LevelMatch lm = new LevelMatch(outPrice, dealNum);
				lm.setEatUp(contrast > -1 ?true:false);
				lms.add(lm);
				input.setList(lms);
				if (contrast == 1) {//水平价格被吃完
					outMap.remove(outPrice);
					input.setState(OrderState.PART.value);
					doMatch(input); // 递归处理
				}else if (contrast == 0) {//都被吃完
					outMap.remove(outPrice);
					input.setState(OrderState.ALL.value);
				}else {//水平价格有剩余
					outMap.compute(outPrice, (k,v) -> v.subtract(dealNum));
					input.setState(OrderState.ALL.value);
				}
			}
		}
	} catch (Exception e) {
		log.error("执行撮合错误:"+e);
		input.setState(3);//撤销掉
	} 
	return input;
}
 
Example 7
Source File: MatchDetailHandler.java    From match-trade with Apache License 2.0 4 votes vote down vote up
/**
 * @Title: outMatchDepth 保证了原子操作,无需事务
 * @Description: TODO(out订单处理)
 * @param @param order 入单
 * @return void 返回类型
 * @throws
 */
@Async
public void outMatchDepth(MatchOrder order) {
	List<LevelMatch> list = order.getList();
	try {
		if (null!=list&&list.size()>0) {
			Iterator<LevelMatch> itr = list.iterator();
			while (itr.hasNext()){
				LevelMatch lm = itr.next();
				itr.remove();
				BigDecimal dealNumber = lm.getNumber();
				while (dealNumber.compareTo(BigDecimal.ZERO)>0) {
					//对手盘
					IMap<Long, MatchOrder> order_map = hzInstance.getMap(HazelcastUtil.getOrderBookKey(order.getCoinTeam(), !order.getIsBuy()));
					@SuppressWarnings("rawtypes")
					Predicate pricePredicate = Predicates.equal("price", lm.getPrice());
					Collection<MatchOrder> orders = order_map.values(pricePredicate);
					for (MatchOrder mor : orders) {
						MatchOrder out = order_map.remove(mor.getId());
						if (null!=out) {
							int cpr = dealNumber.compareTo(out.getUnFinishNumber());
							if (cpr>0) {
								dealNumber=dealNumber.subtract(out.getUnFinishNumber());
								this.updateOutOder(out, OrderState.ALL, out.getUnFinishNumber());
							}else if (cpr==0) {
								this.updateOutOder(out, OrderState.ALL, dealNumber);
								dealNumber = BigDecimal.ZERO;
								break;
							}else {
								out = this.updateOutOder(out, OrderState.PART, dealNumber);
								order_map.put(out.getId(), out);
								dealNumber = BigDecimal.ZERO;
								break;
							}
						}
					}
				}
			}
		}
	} catch (Exception e) {
		log.error("===出单数据处理异常,数据原型:"+order.toJsonString()+"   本次异常:"+e);
	}
}
 
Example 8
Source File: Oauth2TokenPostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> handleRefreshToken(HttpServerExchange exchange, Map<String, Object> formMap) throws ApiException {
    String refreshToken = (String)formMap.get("refresh_token");
    String scope = (String) formMap.get("scope");
    // Get csrf token from the input. every time a new token is generated, a new csrf token will be used.
    String csrf = (String)formMap.get("csrf");
    if(logger.isDebugEnabled()) logger.debug("refreshToken = " + refreshToken + " scope = " + scope);
    Client client = authenticateClient(exchange, formMap);
    if(client != null) {
        // make sure that the refresh token can be found and client_id matches.
        IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
        RefreshToken token = tokens.remove(refreshToken);
        if(token != null) {
            String userId = token.getUserId();
            String userType = token.getUserType();
            String roles = token.getRoles();
            String clientId = token.getClientId();
            String oldScope = token.getScope();
            String remember = token.getRemember();

            if(client.getClientId().equals(clientId)) {
                if(scope == null) {
                    scope = oldScope; // use the previous scope when access token is generated
                } else {
                    // make sure scope is the same as oldScope or contained in oldScope.
                    if(!matchScope(scope, oldScope)) {
                        throw new ApiException(new Status(MISMATCH_SCOPE, scope, oldScope));
                    }
                }
                String jwt;
                Map<String, Object> customMap = null;
                // assume that the custom_claim is in format of json map string.
                String customClaim = client.getCustomClaim();
                try {
                    if(customClaim != null && customClaim.length() > 0) {
                        customMap = Config.getInstance().getMapper().readValue(customClaim, new TypeReference<Map<String, Object>>(){});
                    }
                    jwt = JwtIssuer.getJwt(mockAcClaims(client.getClientId(), scope, userId, userType, roles, csrf, customMap));
                } catch (Exception e) {
                    throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage()));
                }
                // generate a new refresh token and associate it with userId and clientId
                String newRefreshToken = UUID.randomUUID().toString();
                RefreshToken newToken = new RefreshToken();
                newToken.setRefreshToken(newRefreshToken);
                newToken.setUserId(userId);
                newToken.setUserType(userType);
                newToken.setRoles(roles);
                newToken.setClientId(client.getClientId());
                newToken.setScope(scope);
                newToken.setRemember(remember);
                tokens.put(newRefreshToken, newToken);
                // if the client type is external, save the jwt to reference map and send the reference
                if(Client.ClientTypeEnum.EXTERNAL == client.getClientType()) {
                    jwt = jwtReference(jwt, client.getDerefClientId());
                }
                Map<String, Object> resMap = new HashMap<>();
                resMap.put("access_token", jwt);
                resMap.put("token_type", "bearer");
                resMap.put("expires_in", config.getExpiredInMinutes()*60);
                resMap.put("refresh_token", newRefreshToken);
                resMap.put("remember", remember);
                return resMap;

            } else {
                // mismatched client id
                throw new ApiException(new Status(MISMATCH_CLIENT_ID, client.getClientId(), clientId));
            }
        } else {
            // refresh token cannot be found.
            throw new ApiException(new Status(REFRESH_TOKEN_NOT_FOUND, refreshToken));
        }
    }
    return new HashMap<>(); // return an empty hash map. this is actually not reachable at all.
}