org.redisson.api.RBucket Java Examples

The following examples show how to use org.redisson.api.RBucket. 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: RedissonReferenceReactiveTest.java    From redisson with Apache License 2.0 8 votes vote down vote up
@Test
public void testReactiveToNormal() throws InterruptedException {
    RBatchReactive batch = redisson.createBatch(BatchOptions.defaults());
    RBucketReactive<Object> b1 = batch.getBucket("b1");
    RBucketReactive<Object> b2 = batch.getBucket("b2");
    RBucketReactive<Object> b3 = batch.getBucket("b3");
    b2.set(b3);
    b1.set(b2);
    b3.set(b1);
    sync(batch.execute());

    RedissonClient lredisson = Redisson.create(redisson.getConfig());
    RBatch b = lredisson.createBatch(BatchOptions.defaults());
    b.getBucket("b1").getAsync();
    b.getBucket("b2").getAsync();
    b.getBucket("b3").getAsync();
    List<RBucket> result = (List<RBucket>)b.execute().getResponses();
    assertEquals("b2", result.get(0).getName());
    assertEquals("b3", result.get(1).getName());
    assertEquals("b1", result.get(2).getName());

    lredisson.shutdown();
}
 
Example #2
Source File: BucketExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    RedissonClient redisson = Redisson.create();
    
    RBucket<String> bucket = redisson.getBucket("test");
    bucket.set("123");
    boolean isUpdated = bucket.compareAndSet("123", "4934");
    String prevObject = bucket.getAndSet("321");
    boolean isSet = bucket.trySet("901");
    long objectSize = bucket.size();
    
    // set with expiration
    bucket.set("value", 10, TimeUnit.SECONDS);
    boolean isNewSet = bucket.trySet("nextValue", 10, TimeUnit.SECONDS);
    
    redisson.shutdown();
}
 
Example #3
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 #4
Source File: KaptchaServiceImpl.java    From gpmall with Apache License 2.0 6 votes vote down vote up
@Override
public KaptchaCodeResponse getKaptchaCode(KaptchaCodeRequest request) {
    KaptchaCodeResponse response=new KaptchaCodeResponse();
    try {
        ImageResult capText = VerifyCodeUtils.VerifyCode(140, 43, 4);
        response.setImageCode(capText.getImg());
        String uuid= UUID.randomUUID().toString();
        RBucket rBucket=redissonClient.getBucket(KAPTCHA_UUID+uuid);
        rBucket.set(capText.getCode());
        rBucket.expire(60, TimeUnit.SECONDS);
        response.setImageCode(capText.getImg());
        response.setUuid(uuid);
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
    }catch (Exception e){
        log.error("KaptchaServiceImpl.getKaptchaCode occur Exception :"+e);
        ExceptionProcessorUtils.wrapperHandlerException(response,e);
    }
    return response;
}
 
Example #5
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 #6
Source File: RedisCacheTest.java    From gcp-token-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetExpire() {
    // Check that the key doesn't exist
    RBucket<byte[]> bucket = client.getBucket("test", ByteArrayCodec.INSTANCE);
    assertNull(bucket.get());

    // Let the backend set the key/value
    int expireIn = 1;
    cache.set("test", "abcd".getBytes(), expireIn);

    // Check that the key/value was correctly set
    assertArrayEquals("abcd".getBytes(), bucket.get());

    // Wait for a while
    try {
        Thread.sleep(expireIn * 1000 + 1);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    // Check that the key/value is now gone
    assertNull(cache.get("test"));
    assertNull(bucket.get());
}
 
Example #7
Source File: AccountServiceImpl.java    From Almost-Famous with MIT License 6 votes vote down vote up
@Override
public Account login(Account account, String clientIp) {
    account = accountDao.getOne(account);
    if (Objects.nonNull(account)) {
        String access_token = TokenGenerator.getToken(account.getUid());
        String refreshToken = TokenGenerator.getToken(account.getUid());
        accountDao.update(account);
        RBucket<Object> bucket = redissonClient.getBucket(KeyPrefix.AdminRedisPrefix.ADMIN_USER_ID + account.getUid());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", access_token);
        jsonObject.put("ip", clientIp);
        jsonObject.put("refresh_token", refreshToken);
        jsonObject.put("current_time", System.currentTimeMillis());
        jsonObject.put("expire_tick", System.currentTimeMillis() + 1800 * 1000);
        jsonObject.put("refresh_tick", System.currentTimeMillis() + 600 * 1000);
        String token = jsonObject.toJSONString();
        account.setToken(token);
        bucket.set(token);
    }
    return account;
}
 
Example #8
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 #9
Source File: ApiAbstract.java    From kkbinlog with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void afterPropertiesSet() {
    ClassPathResource classPathResource = new ClassPathResource("api.json");
    try (InputStreamReader reader = new InputStreamReader(classPathResource.getInputStream(),"utf-8")) {
        StringBuilder api = new StringBuilder();
        int tempchar;
        while ((tempchar = reader.read()) != -1) {
            api.append((char) tempchar);
        }
        String roleResource = api.toString();
        if(!StringUtils.isEmpty(roleResource)){
            RBucket<Object> bucket = redissonClient.getBucket(clientId.concat("_").concat("resource"));
            bucket.set(roleResource);
            logger.info("初始化or更新url资源完成:" + roleResource);
        }
    } catch (IOException e) {
        logger.error("Api抽取上传失败", e);
    }
}
 
Example #10
Source File: RedissonTest.java    From java-tutorial with MIT License 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    Config config = new Config();
    SingleServerConfig singleServerConfig = config.useSingleServer();
    singleServerConfig.setAddress(redssionProperties.getAddress());
    singleServerConfig.setPassword(redssionProperties.getPassword());

    RedissonClient redissonClient = RedisUtils.getInstance().getRedisson(config);
    RBucket<Object> rBucket = RedisUtils.getInstance().getRBucket(redissonClient, "key");

    System.out.println(rBucket.get());
    while (true) {
        RLock lock = redissonClient.getLock("com.lock");
        lock.tryLock(0, 1, TimeUnit.SECONDS);
        try {
            System.out.println("执行");
        } finally {
            lock.unlock();
        }
    }


}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: RedisCache.java    From t-io with Apache License 2.0 6 votes vote down vote up
@Override
public void put(String key, Serializable value) {
	if (StrUtil.isBlank(key)) {
		return;
	}
	RBucket<Serializable> bucket = getBucket(key);

	long _timeout = timeout;
	if (timeToLiveSeconds != null && timeToLiveSeconds > 0) { //是按timeToLiveSeconds来的
		long ttl = ttl(key);
		if (ttl > 0) {
			_timeout = ttl / 1000;
		}
	}

	bucket.set(value, _timeout, TimeUnit.SECONDS);
}
 
Example #16
Source File: BucketExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();
    
    RBucket<String> bucket = redisson.getBucket("test");
    bucket.set("123");
    boolean isUpdated = bucket.compareAndSet("123", "4934");
    String prevObject = bucket.getAndSet("321");
    boolean isSet = bucket.trySet("901");
    long objectSize = bucket.size();
    
    // set with expiration
    bucket.set("value", 10, TimeUnit.SECONDS);
    boolean isNewSet = bucket.trySet("nextValue", 10, TimeUnit.SECONDS);
    
    redisson.shutdown();
}
 
Example #17
Source File: TransactionExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();
    
    RBucket<String> b = redisson.getBucket("test");
    b.set("123");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBucket<String> bucket = transaction.getBucket("test");
    bucket.set("234");
    
    RMap<String, String> map = transaction.getMap("myMap");
    map.put("1", "2");
    
    transaction.commit();
}
 
Example #18
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/redisson-case")
@ResponseBody
public String redissonCase() {
    RBucket<String> bucket = client.getBucket("key_a");
    bucket.set("value_a");
    RBatch batch = client.createBatch();
    batch.getBucket("batch_k_a").setAsync("batch_v_a");
    batch.getBucket("batch_k_b").setAsync("batch_v_b");
    batch.getBucket("batch_k_b").expireAsync(20, TimeUnit.SECONDS);
    batch.execute();
    return "Success";
}
 
Example #19
Source File: RedissonTransactionalBucketsTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSet() {
    RBucket<String> b1 = redisson.getBucket("test1");
    b1.set("1");
    RBucket<String> b2 = redisson.getBucket("test2");
    b2.set("2");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBuckets buckets = transaction.getBuckets();
    Map<String, Object> bbs = new LinkedHashMap<>();
    bbs.put("test1", "11");
    bbs.put("test2", "22");
    buckets.set(bbs);
    
    Map<String, Object> newBuckets = buckets.get("test1", "test2");
    assertThat(newBuckets).isEqualTo(bbs);
    
    transaction.commit();
    
    assertThat(redisson.getBuckets().get("test1", "test2")).isEqualTo(bbs);
    assertThat(redisson.getKeys().count()).isEqualTo(2);
}
 
Example #20
Source File: RedissonTransactionalBucketTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeout() throws InterruptedException {
    RBucket<String> b = redisson.getBucket("test");
    b.set("123");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults().timeout(3, TimeUnit.SECONDS));
    RBucket<String> bucket = transaction.getBucket("test");
    bucket.set("234");
    
    Thread.sleep(4000);
    
    try {
        transaction.commit();
        Assert.fail();
    } catch (TransactionException e) {
        // skip
    }
    
    Thread.sleep(1000);
    
    assertThat(b.get()).isEqualTo("123");
}
 
Example #21
Source File: RedissonTransactionalBucketTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAndSet() {
    RBucket<String> b = redisson.getBucket("test");
    b.set("123");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBucket<String> bucket = transaction.getBucket("test");
    assertThat(bucket.getAndSet("0")).isEqualTo("123");
    assertThat(bucket.get()).isEqualTo("0");
    assertThat(bucket.getAndSet("324")).isEqualTo("0");
    
    transaction.commit();
    
    assertThat(redisson.getKeys().count()).isEqualTo(1);
    assertThat(b.get()).isEqualTo("324");
}
 
Example #22
Source File: RedissonTransactionalBucketTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompareAndSet() {
    RBucket<String> b = redisson.getBucket("test");
    b.set("123");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBucket<String> bucket = transaction.getBucket("test");
    assertThat(bucket.compareAndSet("0", "434")).isFalse();
    assertThat(bucket.get()).isEqualTo("123");
    assertThat(bucket.compareAndSet("123", "232")).isTrue();
    assertThat(bucket.get()).isEqualTo("232");
    
    transaction.commit();
    
    assertThat(redisson.getKeys().count()).isEqualTo(1);
    assertThat(b.get()).isEqualTo("232");
}
 
Example #23
Source File: RedissonTransactionalBucketTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrySet() {
    RBucket<String> b = redisson.getBucket("test");
    b.set("123");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBucket<String> bucket = transaction.getBucket("test");
    assertThat(bucket.trySet("0")).isFalse();
    assertThat(bucket.delete()).isTrue();
    assertThat(bucket.trySet("324")).isTrue();
    assertThat(bucket.trySet("43")).isFalse();
    
    transaction.commit();
    
    assertThat(redisson.getKeys().count()).isEqualTo(1);
    assertThat(b.get()).isEqualTo("324");
}
 
Example #24
Source File: RedissonTransactionalBucketTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollback() {
    RBucket<Object> b = redisson.getBucket("test");
    b.set("1234");
    
    RTransaction transaction = redisson.createTransaction(TransactionOptions.defaults());
    RBucket<Object> bucket = transaction.getBucket("test");
    assertThat(bucket.get()).isEqualTo("1234");
    assertThat(bucket.getAndDelete()).isEqualTo("1234");
    
    assertThat(b.get()).isEqualTo("1234");
    
    transaction.rollback();
    
    assertThat(redisson.getKeys().count()).isEqualTo(1);
    
    assertThat(b.get()).isEqualTo("1234");
}
 
Example #25
Source File: RedissonBucketsTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrySet() {
    redisson.getBucket("12").set("341");

    Map<String, Integer> buckets = new HashMap<String, Integer>();
    buckets.put("12", 1);
    buckets.put("41", 2);
    assertThat(redisson.getBuckets().trySet(buckets)).isFalse();

    RBucket<Object> r2 = redisson.getBucket("41");
    assertThat(r2.get()).isNull();
    
    Map<String, Integer> buckets2 = new HashMap<String, Integer>();
    buckets2.put("61", 1);
    buckets2.put("41", 2);
    assertThat(redisson.getBuckets().trySet(buckets2)).isTrue();

    RBucket<Object> r1 = redisson.getBucket("61");
    assertThat(r1.get()).isEqualTo(1);

    RBucket<Object> r3 = redisson.getBucket("41");
    assertThat(r3.get()).isEqualTo(2);
}
 
Example #26
Source File: RedissonKeysTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteByPattern() {
    RBucket<String> bucket = redisson.getBucket("test0");
    bucket.set("someValue3");
    assertThat(bucket.isExists()).isTrue();

    RBucket<String> bucket2 = redisson.getBucket("test9");
    bucket2.set("someValue4");
    assertThat(bucket.isExists()).isTrue();

    RMap<String, String> map = redisson.getMap("test2");
    map.fastPut("1", "2");
    assertThat(map.isExists()).isTrue();

    RMap<String, String> map2 = redisson.getMap("test3");
    map2.fastPut("1", "5");
    assertThat(map2.isExists()).isTrue();


    Assert.assertEquals(4, redisson.getKeys().deleteByPattern("test?"));
    Assert.assertEquals(0, redisson.getKeys().deleteByPattern("test?"));
}
 
Example #27
Source File: RedissonKeysTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteByPatternBatch() {
    RBucket<String> bucket = redisson.getBucket("test0");
    bucket.set("someValue3");
    assertThat(bucket.isExists()).isTrue();

    RBucket<String> bucket2 = redisson.getBucket("test9");
    bucket2.set("someValue4");
    assertThat(bucket.isExists()).isTrue();

    RMap<String, String> map = redisson.getMap("test2");
    map.fastPut("1", "2");
    assertThat(map.isExists()).isTrue();

    RMap<String, String> map2 = redisson.getMap("test3");
    map2.fastPut("1", "5");
    assertThat(map2.isExists()).isTrue();


    RBatch batch = redisson.createBatch();
    batch.getKeys().deleteByPatternAsync("test?");
    BatchResult<?> r = batch.execute();
    Assert.assertEquals(4L, r.getResponses().get(0));
}
 
Example #28
Source File: RedissonKeysTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testMassDelete() {
    RBucket<String> bucket0 = redisson.getBucket("test0");
    bucket0.set("someValue");
    RBucket<String> bucket1 = redisson.getBucket("test1");
    bucket1.set("someValue");
    RBucket<String> bucket2 = redisson.getBucket("test2");
    bucket2.set("someValue");
    RBucket<String> bucket3 = redisson.getBucket("test3");
    bucket3.set("someValue");
    RBucket<String> bucket10 = redisson.getBucket("test10");
    bucket10.set("someValue");

    RBucket<String> bucket12 = redisson.getBucket("test12");
    bucket12.set("someValue");
    RMap<String, String> map = redisson.getMap("map2");
    map.fastPut("1", "2");

    Assert.assertEquals(7, redisson.getKeys().delete("test0", "test1", "test2", "test3", "test10", "test12", "map2"));
    Assert.assertEquals(0, redisson.getKeys().delete("test0", "test1", "test2", "test3", "test10", "test12", "map2"));
}
 
Example #29
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 #30
Source File: RedissonLockHeavyTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void lockUnlockRLock() throws Exception {
    for (int i = 0; i < threads; i++) {

        Runnable worker = new Runnable() {

            @Override
            public void run() {
                for (int j = 0; j < loops; j++) {
                    RLock lock = redisson.getLock("RLOCK_" + j);
                    lock.lock();
                    try {
                        RBucket<String> bucket = redisson.getBucket("RBUCKET_" + j);
                        bucket.set("TEST", 30, TimeUnit.SECONDS);
                        RSemaphore semaphore = redisson.getSemaphore("SEMAPHORE_" + j);
                        semaphore.release();
                        try {
                            semaphore.acquire();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };
        executor.execute(worker);
    }
    executor.shutdown();
    executor.awaitTermination(threads * loops, TimeUnit.SECONDS);

}