Java Code Examples for org.redisson.Redisson#create()

The following examples show how to use org.redisson.Redisson#create() . 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: RedissonAutoConfig.java    From kk-anti-reptile with Apache License 2.0 7 votes vote down vote up
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean
RedissonClient redisson() throws Exception {
    Config config = new Config();
    config.useSingleServer().setAddress(address)
            .setConnectionMinimumIdleSize(connectionMinimumIdleSize)
            .setConnectionPoolSize(connectionPoolSize)
            .setDatabase(database)
            .setDnsMonitoringInterval(dnsMonitoringInterval)
            .setSubscriptionConnectionMinimumIdleSize(subscriptionConnectionMinimumIdleSize)
            .setSubscriptionConnectionPoolSize(subscriptionConnectionPoolSize)
            .setSubscriptionsPerConnection(subscriptionsPerConnection)
            .setClientName(clientName)
            .setRetryAttempts(retryAttempts)
            .setRetryInterval(retryInterval)
            .setTimeout(timeout)
            .setConnectTimeout(connectTimeout)
            .setIdleConnectionTimeout(idleConnectionTimeout)
            .setPassword(password);
    Codec codec=(Codec) ClassUtils.forName(getCodec(), ClassUtils.getDefaultClassLoader()).newInstance();
    config.setCodec(codec);
    config.setEventLoopGroup(new NioEventLoopGroup());
    return Redisson.create(config);
}
 
Example 2
Source File: RedisInitializer.java    From tio-starters with MIT License 6 votes vote down vote up
/**
 * @author kuangyoubo
 * @author fanpan26
 * 优先级
 * 通过名字注入 > 配置文件 > 参数配置 > 默认
 */
private void initRedis() {
    if( redisConfig.useInjectRedissonClient() ) {
        logger.info("Get the RedissonClient through injection, Bean name is \"{}\"", redisConfig.getClientBeanName());

        try {
            redissonClient = applicationContext.getBean(redisConfig.getClientBeanName(), RedissonClient.class);
            return;
        } catch (BeansException e) {
            logger.warn("RedissonClient is not found, Recreate RedissonClient on configuration information.");
        }
    }

    /**
     * 优先级
     * 配置文件 > 参数配置 > 默认
     */
    Config config = getConfigByFile();
    if(config == null) {
        config = redisConfig.useConfigParameter() ? redisConfig.getClusterOrSentinelConfig() : getSingleServerConfig();
    }
    redissonClient = Redisson.create(config);
}
 
Example 3
Source File: RedissonTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  final Config config = new Config();
  config.useSingleServer().setAddress("redis://127.0.0.1:6379");

  final RedissonClient redissonClient = Redisson.create(config);
  final RMap<String,String> map = redissonClient.getMap("map");

  map.put("key", "value");
  assertEquals("value", map.get("key"));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  redissonClient.shutdown();
}
 
Example 4
Source File: RedissonClusterConnectionTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void before() throws FailedToStartRedisException, IOException, InterruptedException {
    RedisRunner master1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner master3 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave1 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave2 = new RedisRunner().randomPort().randomDir().nosave();
    RedisRunner slave3 = new RedisRunner().randomPort().randomDir().nosave();

    
    ClusterRunner clusterRunner = new ClusterRunner()
            .addNode(master1, slave1)
            .addNode(master2, slave2)
            .addNode(master3, slave3);
    process = clusterRunner.run();
    
    Config config = new Config();
    config.useClusterServers()
    .setSubscriptionMode(SubscriptionMode.SLAVE)
    .setLoadBalancer(new RandomLoadBalancer())
    .addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
    
    redisson = Redisson.create(config);
    connection = new RedissonClusterConnection(redisson);
}
 
Example 5
Source File: RedissonAutoConfiguration.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
/**
     * 哨兵模式自动装配
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "redisson.master-name")
    RedissonClient redissonSentinel() {
        Config config = new Config();
        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redssionProperties.getSentinelAddresses())
                .setMasterName(redssionProperties.getMasterName())
                .setTimeout(redssionProperties.getTimeout())
                .setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize())
                .setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize());

//        if(StringUtils.isNotBlank(redssionProperties.getPassword())) {
//            serverConfig.setPassword(redssionProperties.getPassword());
//        }
        return Redisson.create(config);
    }
 
Example 6
Source File: StreamExamples.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();
    
    RStream<String, String> stream = redisson.getStream("test");
    stream.createGroup("testGroup");
    
    StreamMessageId id1 = stream.add("1", "1");
    StreamMessageId id2 = stream.add("2", "2");
    
    // contains 2 elements
    Map<StreamMessageId, Map<String, String>> map1 = stream.readGroup("testGroup", "consumer1");

    // ack messages
    stream.ack("testGroup", id1, id2);
    
    StreamMessageId id3 = stream.add("3", "3");
    StreamMessageId id4 = stream.add("4", "4");
    
    // contains next 2 elements
    Map<StreamMessageId, Map<String, String>> map2 = stream.readGroup("testGroup", "consumer2");

    PendingResult pi = stream.listPending("testGroup");
    
    redisson.shutdown();
}
 
Example 7
Source File: RedissonIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMultipleLocksSet_thenEnsureAllCanUnlock(){
    RedissonClient clientInstance1 = Redisson.create();
    RedissonClient clientInstance2 = Redisson.create();
    RedissonClient clientInstance3 = Redisson.create();

    RLock lock1 = clientInstance1.getLock("lock1");
    RLock lock2 = clientInstance2.getLock("lock2");
    RLock lock3 = clientInstance3.getLock("lock3");

    RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
    lock.lock();
    assertTrue(lock1.isLocked() && lock2.isLocked() && lock3.isLocked());

    lock.unlock();
    assertTrue(!(lock1.isLocked() || lock2.isLocked() || lock3.isLocked()));
}
 
Example 8
Source File: AtomicDoubleExamples.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();

    RAtomicDouble atomicDouble = redisson.getAtomicDouble("myDouble");
    atomicDouble.getAndDecrement();
    atomicDouble.getAndIncrement();
    
    atomicDouble.addAndGet(10.323);
    atomicDouble.compareAndSet(29.4, 412.91);
    
    atomicDouble.decrementAndGet();
    atomicDouble.incrementAndGet();
    
    atomicDouble.getAndAdd(302.00);
    atomicDouble.getAndDecrement();
    atomicDouble.getAndIncrement();
    
    redisson.shutdown();
}
 
Example 9
Source File: RedisInitializer.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * @author kuangyoubo
 * @author fanpan26
 * 优先级
 * 通过名字注入 > 配置文件 > 参数配置 > 默认
 */
private void initRedis() {
    if( redisConfig.useInjectRedissonClient() ) {
        logger.info("Get the RedissonClient through injection, Bean name is \"{}\"", redisConfig.getClientBeanName());

        try {
            redissonClient = applicationContext.getBean(redisConfig.getClientBeanName(), RedissonClient.class);
            return;
        } catch (BeansException e) {
            logger.warn("RedissonClient is not found, Recreate RedissonClient on configuration information.");
        }
    }

    /**
     * 优先级
     * 配置文件 > 参数配置 > 默认
     */
    Config config = getConfigByFile();
    if(config == null) {
        config = redisConfig.useConfigParameter() ? redisConfig.getClusterOrSentinelConfig() : getSingleServerConfig();
    }
    redissonClient = Redisson.create(config);
}
 
Example 10
Source File: RedisConfiguration.java    From heimdall with Apache License 2.0 5 votes vote down vote up
private RedissonClient createConnection(int database) {

          Config config = new Config();
          config.useSingleServer()
                  .setAddress(property.getRedis().getHost() + ":" + property.getRedis().getPort())
                  .setConnectionPoolSize(property.getRedis().getConnectionPoolSize())
                  .setDatabase(database);

          return Redisson.create(config);
     }
 
Example 11
Source File: RedisUserTokenManagerTests.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
        RedissonClient client = Redisson.create();

        try {
            ConcurrentMap<String, SimpleUserToken> repo = client.getMap("hsweb.user-token", new SerializationCodec());
            ConcurrentMap<String, Set<String>> userRepo = client.getMap("hsweb.user-token-u", new SerializationCodec());

            userTokenManager = new DefaultUserTokenManager(repo, userRepo) {
                @Override
                protected Set<String> getUserToken(String userId) {
                    userRepo.computeIfAbsent(userId,u->new HashSet<>());

                    return client.getSet("hsweb.user-token-"+userId, new SerializationCodec());
                }

            };

            userTokenManager.setAllopatricLoginMode(AllopatricLoginMode.deny);
//            userTokenManager=new DefaultUserTokenManager();


//            userRepo.clear();
//            repo.clear();
//            for (int i = 0; i < 1000; i++) {
//                userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin", 60*3600*1000);
//            }
//            userTokenManager.signIn(IDGenerator.MD5.generate(), "sessionId", "admin2", 60*3600*1000);

            testGet();
            testGetAll();
            testSignOut();

            testGetAll();
        } finally {
            client.shutdown();
        }
    }
 
Example 12
Source File: SeimiCrawlerBaseConfig.java    From SeimiCrawler with Apache License 2.0 5 votes vote down vote up
@Bean
@Conditional(StandaloneCondition.class)
public RedissonClient initRedisson(){
    SeimiConfig config = CrawlerCache.getConfig();
    if (config == null||!config.isEnableRedissonQueue()){
        return null;
    }
    return Redisson.create(config.getRedissonConfig());
}
 
Example 13
Source File: RedissonLockTest.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static LockManager createLockFactory() {
        if (lockManager != null) {
            return lockManager;
        }
        Config config = new Config();
//        config.setUseLinuxNativeEpoll(true);
        config.useSingleServer().setAddress("redis://127.0.0.1:6379");
        redisson = (Redisson) Redisson.create(config);
        return lockManager = new RedissonLockManager(redisson);
    }
 
Example 14
Source File: RedissionUtils.java    From Redis_Learning with Apache License 2.0 5 votes vote down vote up
/** 
 * ʹ��ip��ַ�Ͷ˿ڴ���Redisson 
 * @param ip 
 * @param port 
 * @return 
 */  
public RedissonClient getRedisson(String ip,String port){  
    Config config=new Config();  
    config.useSingleServer().setAddress(ip+":"+port);  
    RedissonClient redisson = Redisson.create(config);  
    System.out.println("�ɹ�����Redis Server"+"\t"+"����"+ip+":"+port+"������");  
    return redisson;  
}
 
Example 15
Source File: RedissonConfigurationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenJavaConfig_thenRedissonConnectToRedis() {
    Config config = new Config();
    config.useSingleServer()
      .setAddress(String.format("redis://127.0.0.1:%s", port));

    client = Redisson.create(config);

    assert(client != null && client.getKeys().count() >= 0);
}
 
Example 16
Source File: QueueExamples.java    From redisson-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();

    RQueue<String> queue = redisson.getQueue("myQueue");
    queue.add("1");
    queue.add("2");
    queue.add("3");
    queue.add("4");
    
    queue.contains("1");
    queue.peek();
    queue.poll();
    queue.element();
    
    for (String string : queue) {
        // iteration through bulk loaded values
    }
    
    boolean removedValue = queue.remove("1");
    queue.removeAll(Arrays.asList("1", "2", "3"));
    queue.containsAll(Arrays.asList("4", "1", "0"));
    
    List<String> secondList = new ArrayList<>();
    secondList.add("4");
    secondList.add("5");
    queue.addAll(secondList);

    RQueue<String> secondQueue = redisson.getQueue("mySecondQueue");
    
    queue.pollLastAndOfferFirstTo(secondQueue.getName());
    
    redisson.shutdown();
}
 
Example 17
Source File: BlockingDequeExamples.java    From redisson-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();

    RBlockingDeque<String> deque = redisson.getBlockingDeque("myQueue");
    deque.add("1");
    deque.add("2");
    deque.add("3");
    deque.add("4");
    
    deque.contains("1");
    deque.peek();
    deque.poll();
    deque.element();
    
    for (String string : deque) {
        // iteration through bulk loaded values
    }
    
    boolean removedValue = deque.remove("1");
    deque.removeAll(Arrays.asList("1", "2", "3"));
    deque.containsAll(Arrays.asList("4", "1", "0"));
    
    List<String> secondList = new ArrayList<>();
    secondList.add("4");
    secondList.add("5");
    deque.addAll(secondList);

    RQueue<String> secondQueue = redisson.getQueue("mySecondQueue");
    
    deque.pollLastAndOfferFirstTo(secondQueue.getName());
    
    deque.addLast("8");
    deque.addFirst("9");
    
    deque.addLast("30");
    deque.addFirst("80");
    
    String firstValue = deque.pollFirst();
    String lastValue = deque.pollLast();
    
    String peekFirstValue = deque.peekFirst();
    String peekLastValue = deque.peekLast();
    
    String firstRemoved = deque.removeFirst();
    String lastRemoved = deque.removeLast();
    
    
    Thread t = new Thread(() -> {
        try {
            String element1 = deque.poll(10, TimeUnit.SECONDS);
            
            String element2 = deque.take();
            
            String element3 = deque.pollFirst(3, TimeUnit.SECONDS);
            
            String element4 = deque.pollLast(3, TimeUnit.SECONDS);
            
            String element5 = deque.takeFirst();
            
            String element6 = deque.takeLast();
            
            String element7 = deque.pollLastAndOfferFirstTo(secondQueue.getName(), 4, TimeUnit.SECONDS);
            
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    
    t.start();
    t.join();

    redisson.shutdown();
}
 
Example 18
Source File: RedissonConnectionFactory.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    if (config != null) {
        redisson = Redisson.create(config);
    }
}
 
Example 19
Source File: MapCacheExamples.java    From redisson-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();
    
    RMapCache<String, Integer> mapCache = redisson.getMapCache("test");
    
    // with ttl = 10 seconds
    Integer prevValue = mapCache.put("1", 10, 10, TimeUnit.SECONDS);
    // with ttl = 15 seconds and maxIdleTime = 5 seconds
    Integer prevValue2 = mapCache.put("2", 20, 15, TimeUnit.SECONDS, 5, TimeUnit.SECONDS);
    // store value permanently 
    Integer prevValue3 = mapCache.put("3", 30);
    
    // with ttl = 30 seconds
    Integer currValue = mapCache.putIfAbsent("4", 40, 30, TimeUnit.SECONDS);
    // with ttl = 40 seconds and maxIdleTime = 10 seconds
    Integer currValue2 = mapCache.putIfAbsent("5", 50, 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
    // try to add new key-value permanently 
    Integer currValue3 = mapCache.putIfAbsent("6", 60);
    
    // use fast* methods when previous value is not required

    // with ttl = 20 seconds
    boolean isNewKey1 = mapCache.fastPut("7", 70, 20, TimeUnit.SECONDS);
    // with ttl = 40 seconds and maxIdleTime = 20 seconds
    boolean isNewKey2 = mapCache.fastPut("8", 80, 40, TimeUnit.SECONDS, 20, TimeUnit.SECONDS);
    // store value permanently 
    boolean isNewKey3 = mapCache.fastPut("9", 90);
    
    // try to add new key-value permanently
    boolean isNewKeyPut = mapCache.fastPutIfAbsent("10", 100);

    boolean contains = mapCache.containsKey("a");
    
    Integer value = mapCache.get("c");
    Integer updatedValue = mapCache.addAndGet("a", 32);
    
    Integer valueSize = mapCache.valueSize("c");
    
    Set<String> keys = new HashSet<String>();
    keys.add("a");
    keys.add("b");
    keys.add("c");
    Map<String, Integer> mapSlice = mapCache.getAll(keys);
    
    // use read* methods to fetch all objects
    Set<String> allKeys = mapCache.readAllKeySet();
    Collection<Integer> allValues = mapCache.readAllValues();
    Set<Entry<String, Integer>> allEntries = mapCache.readAllEntrySet();
    
    redisson.shutdown();
}
 
Example 20
Source File: PurchaseOrderServiceImpl.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@Transactional
    @Override
    public AssembleDetailVo joinExistsAssemble(Integer assembleId,Integer skuId,Integer count,Integer shippingId) {
        //加入已经存在的拼单
        Assemble assemble = assembleMapper.selectByPrimaryKey(assembleId);
        Objects.requireNonNull(assemble,"当前拼单不存在");
        if (assemble.getStatus()==0){
            throw new ParamException("当前拼单已经失效,无法加入当前拼单");
        }
        if (assemble.getStatus()==2){
            throw new ParamException("拼单人数已满,加入拼单失败");
        }
        checkSpellArguments(assemble.getProductId(),count);
        //使用分布式锁
        Config config = new Config();
        config.useSingleServer()
                .setAddress(RedisConstant.Redisson.REDIS_ADDRESS);
        RedissonClient redisson = Redisson.create(config);
        RLock lock = redisson.getLock(RedisConstant.Redisson.LOCK_SPELL_ORDER);
        boolean locked = false;
        try{
            log.info("尝试获取拼单锁");
            locked = lock.tryLock(10,TimeUnit.SECONDS);
            log.info("获取锁的状态:{}",locked);
            if(locked){
                User user=AuthenticationInfoUtil.getUser(userMapper,memcachedClient);
                AssembleItem assembleItem=new AssembleItem();
                assembleItem.setNickname(user.getNickname());
                assembleItem.setAvatar(user.getAvatar());
                assembleItem.setAssembleId(assembleId);
                assembleItemMapper.insert(assembleItem);
//                assemble.getAssembleItems().add(assembleItem);
                assemble.setStatus(2);//拼单完成,开始进入订单生效阶段
                assembleMapper.updateByPrimaryKeySelective(assemble);
                generateOrder(user,skuId,count,assemble,shippingId);

                //更新订单下的所有发货信息,异步操作
                this.rabbitTemplate.convertAndSend(UPDATE_ORDER_EXCHANGE,"",String.valueOf(assembleId));
                rabbitTemplate.convertAndSend(ChengfengConstant.RabbitMQ.UPDATE_ORDER_EXCHANGE,
                        "update_order_queue",String.valueOf(assembleId) , message -> {
                            message.getMessageProperties().setHeader("x-delay",5000);
                            return message;
                        });
                log.info("得到锁并且完成拼单操作");
            }
            AssembleDetailVo assembleDetailVo=new AssembleDetailVo();
            BeanUtils.copyProperties(assemble,assembleDetailVo);
            List<AssembleItem> assembleItemList=Lists.newArrayList();
            assembleDetailVo.setAssembleItemList(assembleItemList);
            assembleDetailVo.getAssembleItemList().addAll( assembleMapper.selectAssembleDetailInfoById(assembleId).getAssembleItems());
            return assembleDetailVo;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log.info("释放锁");
            if(locked){
                lock.unlock();
            }
        }
        return null;
    }