Java Code Examples for org.redisson.api.RBucket#get()

The following examples show how to use org.redisson.api.RBucket#get() . 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: UserRepository.java    From j360-dubbo-app-all with Apache License 2.0 6 votes vote down vote up
/**
 * redission 作为二级缓存DAO层的案例
 * @param id
 * @return
 */
public String getUserCacheable(long id) {
    try{
        RBucket<String> rBucket = redissonClient.getBucket(String.format(UserKeys.USER_DO_ID, id, JsonJacksonCodec.INSTANCE));
        if (rBucket.isExists()) {
            rBucket.expire(AppConfig.COMMON_CACHE_DAYS, TimeUnit.MINUTES);
            return rBucket.get();
        }
        String name = jdbcTemplate.queryForObject("select username from user where id = ?", String.class, new Object[]{id});
        if (Objects.nonNull(name)) {
            redissonClient.getBucket(String.format(UserKeys.USER_DO_ID, id),JsonJacksonCodec.INSTANCE)
                    .setAsync(name, AppConfig.COMMON_CACHE_DAYS, TimeUnit.MINUTES);
        }
        return name;
    }catch(Throwable th){
        throw new RepositoryException(ErrorCode.DB_ERROR.getErrorCode(),ErrorCode.DB_ERROR.getErrorMsg(),th);
    }

}
 
Example 2
Source File: UserRepository.java    From j360-dubbo-app-all with Apache License 2.0 6 votes vote down vote up
/**
 * redission 作为二级缓存DAO层的案例
 * @param itemId
 * @return
 */
public UserDO getGoodsCacheable(long itemId) {
    try{
        RBucket<UserDO> rBucket = redissonClient.getBucket(String.format(UserKeys.USER_DO_ID, itemId, JsonJacksonCodec.INSTANCE));
        if (rBucket.isExists()) {
            rBucket.expire(AppConfig.COMMON_CACHE_DAYS, TimeUnit.MINUTES);
            return rBucket.get();
        }
        UserDO topicDO = getGoods(itemId);
        if (Objects.nonNull(topicDO)) {
            redissonClient.getBucket(String.format(UserKeys.USER_DO_ID, itemId),JsonJacksonCodec.INSTANCE)
                    .setAsync(topicDO, AppConfig.COMMON_CACHE_DAYS, TimeUnit.MINUTES);
        }
        return topicDO;
    }catch(Throwable th){
        throw new RepositoryException(ErrorCode.DB_ERROR.getErrorCode(),ErrorCode.DB_ERROR.getErrorMsg(),th);
    }

}
 
Example 3
Source File: DesignElementService.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
@Override
public String findApplications() {
    String path = ElementType.MetaApplication.name();
    RBucket<String> cache = redisson.getBucket(path, StringCodec.INSTANCE);
    String result = cache.get();
    if (result == null) {
        // 缓存中没有,从数据库加载
        List<String> contents = repository
                .findContent(StringHelper.join(path, ":%"));
        List<MetaApplicationImpl> applications = new ArrayList<>(
                contents.size());
        for (String content : contents) {
            MetaApplicationImpl application = SerializeUtil.parseObject(
                    content, MetaApplicationImpl.class);
            applications.add(application);
        }
        result = SerializeUtil.toString(applications);
        cache.set(result, CACHE_EXPIRE_DAY, TimeUnit.DAYS);
    }
    return result;
}
 
Example 4
Source File: RedisCache.java    From t-io with Apache License 2.0 6 votes vote down vote up
@Override
public Serializable _get(String key) {
	if (StrUtil.isBlank(key)) {
		return null;
	}
	RBucket<Serializable> bucket = getBucket(key);
	if (bucket == null) {
		log.error("bucket is null, key:{}", key);
		return null;
	}
	Serializable ret = bucket.get();
	if (timeToIdleSeconds != null) {
		if (ret != null) {
			//				bucket.expire(timeout, TimeUnit.SECONDS);
			RedisExpireUpdateTask.add(cacheName, key, timeout);
		}
	}
	return ret;
}
 
Example 5
Source File: CacheInterceptorService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the request is in cache. If true then returns the cached response, otherwise
 * continues the request normally and signals to create the cache for this request.
 *
 * @param cacheName   Cache name provided
 * @param timeToLive  How much time the cache will live (0 or less to live forever)
 * @param headers     List of headers that when present signal that the request should be cached
 * @param queryParams List of queryParams that when present signal that the request should be cached
 */
public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) {

    RequestContext context = RequestContext.getCurrentContext();

    boolean responseFromCache = false;

    if (shouldCache(context, headers, queryParams)) {
        RBucket<ApiResponse> rBucket = redissonClientCacheInterceptor.getBucket(createCacheKey(context, cacheName, headers, queryParams));

        if (rBucket.get() == null) {
            context.put(CACHE_BUCKET, rBucket);
            context.put(CACHE_TIME_TO_LIVE, timeToLive);
        } else {
            ApiResponse response = rBucket.get();

            helper.call().response().header().addAll(response.getHeaders());
            helper.call().response().setBody(response.getBody());
            helper.call().response().setStatus(response.getStatus());
            context.setSendZuulResponse(false);
            responseFromCache = true;
        }
    }

    TraceContextHolder.getInstance().getActualTrace().setCache(responseFromCache);
}
 
Example 6
Source File: KaptchaServiceImpl.java    From gpmall with Apache License 2.0 6 votes vote down vote up
@Override
public KaptchaCodeResponse validateKaptchaCode(KaptchaCodeRequest request) {
    KaptchaCodeResponse response=new KaptchaCodeResponse();
    try{
        request.requestCheck();
        String redisKey = KAPTCHA_UUID+request.getUuid();
        RBucket<String> rBucket=redissonClient.getBucket(redisKey);
        String code=rBucket.get();
        log.info("请求的redisKey={},请求的code={},从redis获得的code={}",redisKey,request.getCode(),code);
        if(StringUtils.isNotBlank(code)&&request.getCode().equalsIgnoreCase(code)){
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            return response;
        }
        response.setCode(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getCode());
        response.setMsg(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
    }catch (Exception e){
        log.error("KaptchaServiceImpl.validateKaptchaCode occur Exception :"+e);
        ExceptionProcessorUtils.wrapperHandlerException(response,e);
    }
    return response;
}
 
Example 7
Source File: AbstractMatch.java    From Almost-Famous with MIT License 6 votes vote down vote up
@Override
public void update(int sid, MatchEnum matchEnum) {
    Session session = LinkMgr.getSession(sid);
    if (null == session) return;
    String match_queue_by_role_key = KeyPrefix.BattleRedisPrefix.MATCH_QUEUE_BY_ROLE + session.getRid();
    RBucket<Actor> bucket = redissonClient.getBucket(match_queue_by_role_key);
    Actor actor = bucket.get();
    if (null == actor) return;
    if (actor.getBattleMode() == BattleModeEnum.RANK) {
        RankMatchMgr rankMatchMgr = SpringContextUtils.getBean("rankMatchMgr", RankMatchMgr.class);
        rankMatchMgr.remove(actor, matchEnum);
    } else if (actor.getBattleMode() == BattleModeEnum.LEISURE) {
        LeisureMatchMgr leisureMatchMgr = SpringContextUtils.getBean("leisureMatchMgr", LeisureMatchMgr.class);
        leisureMatchMgr.remove(actor, matchEnum);
    }
    bucket.delete();
}
 
Example 8
Source File: DesignElementService.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public String get(String id) {
    RBucket<String> cache = redisson.getBucket(id, StringCodec.INSTANCE);
    String result = cache.get();
    if (result == null) {
        Optional<DesignElement> entity = repository.findById(id);
        if (entity.isPresent()) {
            result = entity.get().getFdContent();
        } else {
            result = JSON_EMPTY;
        }
        cache.set(result, CACHE_EXPIRE_DAY, TimeUnit.DAYS);
    }
    return result;
}
 
Example 9
Source File: RedissionUtilsTest.java    From Redis_Learning with Apache License 2.0 5 votes vote down vote up
/** 
 * RBucket ӳ��Ϊ redis server �� string ���� 
 * ֻ�ܴ�����洢��һ���ַ��� 
 * redis server ����: 
 * �鿴���м�---->keys * 
 * �鿴key������--->type testBucket 
 * �鿴key��ֵ ---->get testBucket 
 */  
@Test  
public void testGetRBucket() {  
    RBucket<String> rBucket=RedissionUtils.getInstance().getRBucket(redisson, "testBucket");  
    //ͬ������  
    rBucket.set("redisBucketASync");  
    //�첽����  
    rBucket.setAsync("����");  
    String bucketString=rBucket.get();  
    System.out.println(bucketString);  
}
 
Example 10
Source File: AbstractMatch.java    From Almost-Famous with MIT License 5 votes vote down vote up
/**
 * @param roleId
 * @return 房间简单信息
 */
public SimpleBattleRoom getSimpleBattleRoomByRoleId(long roleId) {
    RBucket<Long> roomId = redissonClient.getBucket(KeyPrefix.BattleRedisPrefix.BATTLE_ROOM_BY_ROLE + roleId);
    if (null == roomId)
        return null;
    RBucket<SimpleBattleRoom> room = redissonClient.getBucket(KeyPrefix.BattleRedisPrefix.BATTLE_ROOM + roomId.get());
    if (null == room)
        return null;
    return room.get();
}
 
Example 11
Source File: ApplicationConfigService.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public String get(String id) {
    RBucket<String> cache = getCache(id);
    String result = cache.get();
    if (result == null) {
        Optional<ApplicationConfig> entity = repository.findById(id);
        if (entity.isPresent()) {
            result = entity.get().getFdContent();
        } else {
            result = JSON_EMPTY;
        }
        cache.set(result, CACHE_EXPIRE_DAY, TimeUnit.DAYS);
    }
    return result;
}
 
Example 12
Source File: DesignElementService.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public String findSummary(String path) {
    RBucket<String> cache = redisson.getBucket(path, StringCodec.INSTANCE);
    String result = cache.get();
    if (result == null) {
        result = listToString(repository.findSummary(
                StringHelper.join(path, ":%")));
        cache.set(result, CACHE_EXPIRE_DAY, TimeUnit.DAYS);
    }
    return result;
}
 
Example 13
Source File: AbstractMatch.java    From Almost-Famous with MIT License 4 votes vote down vote up
public boolean isHaveBattleRoom(long roleId) {
    RBucket<Long> roomId = redissonClient.getBucket(KeyPrefix.BattleRedisPrefix.BATTLE_ROOM_BY_ROLE + roleId);
    return roomId.get() == null ? false : true;
}
 
Example 14
Source File: RedisCache.java    From gcp-token-broker with Apache License 2.0 4 votes vote down vote up
public byte[] get(String key) {
    RBucket<byte[]> bucket = getClient().getBucket(key, ByteArrayCodec.INSTANCE);
    return bucket.get();
}
 
Example 15
Source File: CreateRoleAction.java    From Almost-Famous with MIT License 4 votes vote down vote up
@Override
    public Resoult execute(JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        Long uid = jsonObject.getLong("uid");
        // 模板中的数据
        // 模板中的数据
        Role role = roleService.selectById(uid);
        if (null == role) {
            String name = Misc.generatorName();
            UniqueNameEnum uniqueNameEnum = rpcClient.uniqueName(name);
            if (uniqueNameEnum != UniqueNameEnum.SUCCESS) {
                return Resoult.error(RegisterProtocol.CREATE_ROLE_ACTION_RESP, ErrorCode.REPEAT_NAME_ERROR, "Repeat name");
            }
            // get role id
            long rid = rpcClient.getUniqueId();
            // check login
            RBucket<String> bucket = redissonClient.getBucket(KeyPrefix.AdminRedisPrefix.ADMIN_USER_ID + uid);
            String token = bucket.get();
            if (token == null) {
                return Resoult.error(RegisterProtocol.CREATE_ROLE_ACTION_RESP, ErrorCode.TOKEN_EXPIRE_ERROR, "Token expire");
            }
            Role r = new Role();
            r.setRoleName(name);
            r.setUid(uid);
            r.setRid(rid);
            // 初始金币
            GlobalVariableConf globalVariable = ConfigManager.globalVariableConfMap.get(1018);
            r.setGold(Long.parseLong(globalVariable.getValue()));
            // 初始银币
            globalVariable = ConfigManager.globalVariableConfMap.get(1019);
            r.setSilver(Long.parseLong(globalVariable.getValue()));
            // 初始钻石
            globalVariable = ConfigManager.globalVariableConfMap.get(1020);
            r.setDiamond(Long.parseLong(globalVariable.getValue()));
            // 初始携带职业
            globalVariable = ConfigManager.globalVariableConfMap.get(1017);
            r.setSchool(Misc.cutQuotes(globalVariable.getValue()));
            String[] schools = Misc.split(globalVariable.getValue(), "\\,");
            if (null != schools && schools.length > 0) {
                for (String school : schools) {
                    int schoolId = Integer.parseInt(school);
                    this.schoolService.addSchoolByRoleId(rid, schoolId);
                }
            }
            // 初始最后战斗职业、最后战斗卡组、新手指引步骤
            r.setLastBattleSchool(0);
            r.setLastBattleCardGroup(0L);
            r.setNewcomerGuide(0);
            // 初始段位
            globalVariable = ConfigManager.globalVariableConfMap.get(1033);
            String[] battleRank = Misc.split(globalVariable.getValue(), "\\,");
            BattleRankBean battleRankBean = new BattleRankBean();
            battleRankBean.setRankId(Integer.parseInt(battleRank[0]));
            battleRankBean.setStarCount(Integer.parseInt(battleRank[1]));
            r.setBattleRank(battleRankBean);
            // save
            roleService.addRole(r);
            // 初始化卡包
            cardPackageService.initCard(rid);
            // 初始化签到奖励
            iSignRewardService.initSignRewardMgr(rid);
            // 初始化任务资源
            iMissionService.initMission(rid);
            // 初始化主线章节
            iChapterService.initChapter(rid);
            // 初始化背包(卡包)
            iBagCardStrategyService.initActorBag(rid);
            // 初始化战报
//            battleHistoryService.initBattleHistory(rid);

            return Resoult.ok(RegisterProtocol.CREATE_ROLE_ACTION_RESP);
        }
        return Resoult.error(RegisterProtocol.CREATE_ROLE_ACTION_RESP, ErrorCode.ROLE_EXIST, "");
    }
 
Example 16
Source File: DesignElementService.java    From mPaaS with Apache License 2.0 4 votes vote down vote up
@Override
public String findExtensions(String pointId) {
    String path = PersistentConstant.toId(ElementType.Extension, pointId);
    RBucket<String> cache = redisson.getBucket(path, StringCodec.INSTANCE);
    String result = cache.get();
    if (result == null) {
        // 缓存中没有,从数据库加载
        List<String> contents = repository
                .findContent(StringHelper.join(path, ":%"));
        List<ExtensionImpl> extensions = new ArrayList<>(contents.size());
        PluginConfig config = getPluginConfig();
        ExtensionImpl selected = null;
        for (String content : contents) {
            ExtensionImpl extension = SerializeUtil.parseObject(content,
                    ExtensionImpl.class);
            String id = PersistentConstant.toId(ElementType.Extension,
                    pointId, extension.getId());
            // 禁用
            if (config.getDisabledExtensions().contains(id)) {
                continue;
            }
            // 选定
            if (config.getSelectedExtensions().contains(id)) {
                selected = extension;
            }
            extensions.add(extension);
        }
        // 取扩展点,根据扩展点进行排序或取单值
        ExtensionPointImpl point = getExtensionPoint(pointId);
        if (point != null) {
            if (point.isOrdered()) {
                Collections.sort(extensions);
            }
            if (point.isSingleton() && extensions.size() > 1) {
                if (selected == null) {
                    selected = extensions.get(0);
                }
                extensions.clear();
                extensions.add(selected);
            }
        }
        result = SerializeUtil.toString(extensions);
        cache.set(result, CACHE_EXPIRE_DAY, TimeUnit.DAYS);
    }
    return result;
}
 
Example 17
Source File: VerifyImageUtil.java    From kk-anti-reptile with Apache License 2.0 4 votes vote down vote up
public String getVerifyCodeFromRedis(String verifyId) {
    String result = null;
    RBucket<String> rBucket = redissonClient.getBucket(VERIFY_CODE_KEY + verifyId);
    result = rBucket.get();
    return result;
}
 
Example 18
Source File: RedissonObject.java    From redisson-spring-boot-starter with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * 获取对象值
 *
 * @param name
 * @param <T>
 * @return
 */
public <T> T getValue(String name) {
    RBucket<T> bucket = redissonClient.getBucket(name);
    return bucket.get();
}