精华内容
下载资源
问答
  • RedissonClient

    千次阅读 2019-07-29 10:38:21
     public DistributedLocker distributedLocker(RedissonClient redissonClient) {  RedissonDistributedLocker locker = new RedissonDistributedLocker();  locker.setRedissonClient(redissonClient);  ...

    package com.sdk.cloud.storge.service.redisservice.config;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    import org.apache.commons.lang.StringUtils;
    import org.redisson.Redisson;
    import org.redisson.api.RedissonClient;
    import org.redisson.config.ClusterServersConfig;
    import org.redisson.config.Config;
    import org.redisson.config.ReadMode;
    import org.redisson.config.SingleServerConfig;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.ImportResource;

    import com.sdk.cloud.storge.service.common.DistributedLocker;
    import com.sdk.cloud.storge.service.redisservice.RedissonLockUtil;
    import com.sdk.cloud.storge.service.redisservice.RedissonDistributedLocker;
    import com.sdk.cloud.storge.service.redisservice.config.RedisModeProperties;

    @ConditionalOnClass(Config.class)
    @Configuration
    @EnableConfigurationProperties(RedisModeProperties.class)
    public class RedisCacheConfiguration {

        @Autowired
        RedisModeProperties redisProperties;
        
        @Configuration
        @ConditionalOnClass({Redisson.class})
        @ConditionalOnExpression("'${spring.redis.mode}'=='single' or '${spring.redis.mode}'=='cluster' or '${spring.redis.mode}'=='sentinel'")
        public  class  RedissonSingleClientConfiguration{
            
            @Bean
            @ConditionalOnProperty(name = "spring.redis.mode", havingValue = "single")
            public RedissonClient  redissonSingle(){
                Config config = new Config();
                String address = redisProperties.getSingle().getAddress();
                address = ((address.startsWith("redis://") ) ? address : "redis://"+address);
                SingleServerConfig serverConfig = config.useSingleServer().setAddress(address).setClientName("Single")
                .setConnectionPoolSize(redisProperties.getPool().getSize())
                .setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle())
                .setConnectTimeout(redisProperties.getPool().getConnTimeout())
                .setDatabase(redisProperties.getDatabase());
                if(StringUtils.isNotBlank(redisProperties.getPassword())) {
                    serverConfig.setPassword(redisProperties.getPassword());
                }
                return  Redisson.create(config);
            }
            
            @SuppressWarnings("deprecation")
            @Bean
            @ConditionalOnProperty(name = "spring.redis.mode", havingValue = "sentinel")
            public RedissonClient redissonSentinel() {
                Config config = new  Config();
                String[] nodes = redisProperties.getSentinel().getNodes().split(",");
                List<String> newNodes = new ArrayList<>(nodes.length);
                Arrays.stream(nodes).forEach((index)->newNodes.add(index.startsWith("redis://") ? index : "redis://" + index));
                config.useSentinelServers()
                .addSentinelAddress(newNodes.toArray(new String[0]))
                .setMasterConnectionPoolSize(redisProperties.getPool().getSize())
                .setSlaveConnectionPoolSize(redisProperties.getPool().getSize())
                .setClientName("Sentinel")
                .setReadMode(ReadMode.SLAVE)
                .setMasterName(redisProperties.getSentinel().getMaster())
                .setDatabase(redisProperties.getDatabase())
                .setFailedAttempts(redisProperties.getSentinel().getFailMax())
                .setTimeout(redisProperties.getTimeout());
                
                
                
                return Redisson.create(config);
            }
            @Bean
            @ConditionalOnProperty(name = "spring.redis.mode", havingValue = "cluster")
            public RedissonClient redissonCluster() {
                 Config config = new Config();
                 String[] nodes = redisProperties.getCluster().getNodes().split(",");
                 ArrayList<String> addresses = new ArrayList<>(nodes.length);
                 Arrays.stream(nodes).forEach((index)->addresses.add(index.startsWith("redis://") ? index : "redis://" + index));
                 ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(addresses.toArray(new String[0]))
                 .setClientName("Cluster")
                 .setConnectTimeout(redisProperties.getTimeout())
                 .setRetryInterval(redisProperties.getCluster().getRetryInterval())
                 .setIdleConnectionTimeout(redisProperties.getPool().getSoTimeout())
                 .setScanInterval(redisProperties.getCluster().getRetryInterval())
                 .setMasterConnectionPoolSize(redisProperties.getCluster().getMasterConnectionPoolSize())
                 .setSlaveConnectionPoolSize(redisProperties.getCluster().getSlaveConnectionPoolSize())
                 .setFailedAttempts(redisProperties.getCluster().getFailedAttempts());
                 if(StringUtils.isNotBlank(redisProperties.getPassword())) {
                     clusterServersConfig.setPassword(redisProperties.getPassword()) ;
                 }
                 return Redisson.create(config);
                 
             }
        
        
        }    
        
        

        /**
         * 装配locker类,并将实例注入到RedissLockUtil中
         * @return
         */
        @Bean
        public DistributedLocker distributedLocker(RedissonClient redissonClient) {
            RedissonDistributedLocker locker = new RedissonDistributedLocker();
            locker.setRedissonClient(redissonClient);
            RedissonLockUtil.setLocker(locker);
            return locker;
        }
        
        
        
        
        
        
    }
     

    展开全文
  • 本文整理汇总了Java中org.redisson.api.RedissonClient类的典型用法代码示例。如果您正苦于以下问题:Java RedissonClient类的具体用法?Java RedissonClient怎么用?Java RedissonClient使用的例子?那么恭喜您, ...

    本文整理汇总了Java中org.redisson.api.RedissonClient类的典型用法代码示例。如果您正苦于以下问题:Java RedissonClient类的具体用法?Java RedissonClient怎么用?Java RedissonClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。

    RedissonClient类属于org.redisson.api包,在下文中一共展示了RedissonClient类的39个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

    示例1: mapsLocalCache2

    ​点赞 4

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    void mapsLocalCache2(Waiter waiter) {

    Config config = new Config();

    config.useSingleServer().setAddress("http://127.0.0.1:6379");

    RedissonClient client = Redisson.create(config);

    LocalCachedMapOptions options = LocalCachedMapOptions.defaults().maxIdle(10 * 1000).timeToLive(10 * 1000);

    RLocalCachedMap map = client.getLocalCachedMap("myMap", options);

    System.out.println("KEY BEFORE: " + map.get("key"));

    try {

    Thread.sleep(2000);

    }

    catch(InterruptedException e) {

    e.printStackTrace();

    }

    System.out.println("KEY AFTER: " + map.get("key"));

    waiter.assertEquals(map.get("key"), 25);

    }

    开发者ID:Superioz,项目名称:MooProject,代码行数:20,

    示例2: createInstance

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    @Override

    public RedissonClient createInstance(int connections, String host) {

    Config c = new Config();

    // c.setUseLinuxNativeEpoll(true);

    // c.useClusterServers()

    c.useSingleServer()

    .setTimeout(10000000)

    .setAddress(host)

    .setConnectionPoolSize(connections).setConnectionMinimumIdleSize(connections);

    // .addNodeAddress(host)

    // .setMasterConnectionPoolSize(connections).setMasterConnectionMinimumIdleSize(connections);

    c.setCodec(StringCodec.INSTANCE);

    RedissonClient r = Redisson.create(c);

    r.getKeys().flushdb();

    return r;

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:18,

    示例3: mapsItemChange2

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    void mapsItemChange2(Waiter waiter){

    Config config = new Config();

    config.useSingleServer().setAddress("http://127.0.0.1:6379");

    RedissonClient client = Redisson.create(config);

    LocalCachedMapOptions options = LocalCachedMapOptions.defaults().maxIdle(10 * 1000).timeToLive(10 * 1000);

    RLocalCachedMap> map = client.getLocalCachedMap("myMap", options);

    FinalValue value = map.get("test");

    System.out.println("Value Before: " + value.get());

    try {

    Thread.sleep(2000);

    }

    catch(InterruptedException e) {

    e.printStackTrace();

    }

    value = map.get("test");

    System.out.println("Value After: " + value.get());

    waiter.assertEquals(value.get(), 18);

    }

    开发者ID:Superioz,项目名称:MooProject,代码行数:22,

    示例4: provider

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static RedissonClient provider() {

    if (client == null) {

    Config config = new Config();

    config.useSingleServer().setAddress("redis://" + REDIS_HOST + ":6379");

    client = Redisson.create(config);

    }

    return client;

    }

    开发者ID:JungleTree,项目名称:JungleTree,代码行数:9,

    示例5: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Bench bench = new RedissonBench() {

    @Override

    public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,

    MetricRegistry metrics) {

    RList list = benchInstance.getList("list_" + threadNumber);

    Timer.Context time = metrics.timer("list").time();

    list.add(data);

    time.stop();

    }

    };

    Benchmark benchmark = new Benchmark(bench);

    benchmark.run(args);

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:17,

    示例6: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Config config = new Config();

    config.useSingleServer().setAddress("127.0.0.1:6379");

    RedissonClient redisson = Redisson.create(config);

    Messager messager = new RedissonMessager(redisson);

    byte[] stat = new byte[1];

    // new Thread(() -> {

    // for (int i = 0; i < 1000; i++) {

    // try {

    // Thread.sleep(1000);

    // } catch (InterruptedException e) {

    // e.printStackTrace();

    // }

    // messager.publish(text("hello2"))

    // .to(topic("test"))

    // .from(user("admin"))

    // .send();

    // }

    // }).start();

    messager.subscribe(topic("test"))

    .onMessage(System.out::println)

    .onMessage(msg -> stat[0] = 1);

    //redisson.shutdown();

    }

    开发者ID:hs-web,项目名称:hsweb-framework,代码行数:27,

    示例7: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RSortedSet sortedSet = redisson.getSortedSet("mySortedSet");

    sortedSet.add("1");

    sortedSet.add("2");

    sortedSet.add("3");

    for (String string : sortedSet) {

    // iteration through bulk loaded values

    }

    String firstValue = sortedSet.first();

    String lastValue = sortedSet.last();

    boolean removedValue = sortedSet.remove("1");

    sortedSet.removeAll(Arrays.asList("1", "2", "3"));

    sortedSet.containsAll(Arrays.asList("4", "1", "0"));

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:23,

    示例8: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    RedissonClient redisson = Redisson.create();

    RBucket 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();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:17,

    示例9: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RLock lock = redisson.getLock("lock");

    lock.lock(2, TimeUnit.SECONDS);

    Thread t = new Thread() {

    public void run() {

    RLock lock1 = redisson.getLock("lock");

    lock1.lock();

    lock1.unlock();

    };

    };

    t.start();

    t.join();

    lock.unlock();

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:23,

    示例10: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RHyperLogLog hyperLogLog = redisson.getHyperLogLog("hyperLogLog");

    hyperLogLog.add("1");

    hyperLogLog.add("2");

    hyperLogLog.add("3");

    hyperLogLog.addAll(Arrays.asList("10", "20", "30"));

    RHyperLogLog hyperLogLog1 = redisson.getHyperLogLog("hyperLogLog1");

    hyperLogLog1.add("4");

    hyperLogLog1.add("5");

    hyperLogLog1.add("6");

    RHyperLogLog hyperLogLog2 = redisson.getHyperLogLog("hyperLogLog2");

    hyperLogLog1.add("4");

    hyperLogLog1.add("5");

    hyperLogLog1.add("6");

    hyperLogLog2.mergeWith(hyperLogLog1.getName());

    hyperLogLog2.countWith(hyperLogLog1.getName());

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:26,

    示例11: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    CountDownLatch latch = new CountDownLatch(1);

    RTopic topic = redisson.getTopic("topic2");

    topic.addListener(new MessageListener() {

    @Override

    public void onMessage(String channel, String msg) {

    latch.countDown();

    }

    });

    topic.publish("msg");

    latch.await();

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:20,

    示例12: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RBucket 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();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:18,

    示例13: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RAtomicLong atomicLong = redisson.getAtomicLong("myLong");

    atomicLong.getAndDecrement();

    atomicLong.getAndIncrement();

    atomicLong.addAndGet(10L);

    atomicLong.compareAndSet(29, 412);

    atomicLong.decrementAndGet();

    atomicLong.incrementAndGet();

    atomicLong.getAndAdd(302);

    atomicLong.getAndDecrement();

    atomicLong.getAndIncrement();

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:21,

    示例14: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    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();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:21,

    示例15: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws IOException {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RBinaryStream stream = redisson.getBinaryStream("myStream");

    byte[] values = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

    stream.trySet(values);

    stream.set(values);

    InputStream is = stream.getInputStream();

    StringBuilder sb = new StringBuilder();

    int ch;

    while((ch = is.read()) != -1) {

    sb.append((char)ch);

    }

    String str = sb.toString();

    OutputStream os = stream.getOutputStream();

    for (int i = 0; i < values.length; i++) {

    byte c = values[i];

    os.write(c);

    }

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:27,

    示例16: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient redisson = Redisson.create();

    RGeo geo = redisson.getGeo("myGeo");

    GeoEntry entry = new GeoEntry(13.361389, 38.115556, "Palermo");

    geo.add(entry);

    geo.add(15.087269, 37.502669, "Catania");

    Double dist = geo.dist("Palermo", "Catania", GeoUnit.METERS);

    Map pos = geo.pos("Palermo", "Catania");

    List cities = geo.radius(15, 37, 200, GeoUnit.KILOMETERS);

    List allNearCities = geo.radius("Palermo", 10, GeoUnit.KILOMETERS);

    Map citiesWithDistance = geo.radiusWithDistance(15, 37, 200, GeoUnit.KILOMETERS);

    Map allNearCitiesDistance = geo.radiusWithDistance("Palermo", 10, GeoUnit.KILOMETERS);

    Map citiesWithPosition = geo.radiusWithPosition(15, 37, 200, GeoUnit.KILOMETERS);

    Map allNearCitiesPosition = geo.radiusWithPosition("Palermo", 10, GeoUnit.KILOMETERS);

    redisson.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:25,

    示例17: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    Config config = new Config();

    config.useClusterServers()

    .addNodeAddress("127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003");

    RedissonClient redisson = Redisson.create(config);

    RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);

    nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor", 1));

    RedissonNode node = RedissonNode.create(nodeConfig);

    node.start();

    RExecutorService e = redisson.getExecutorService("myExecutor");

    e.execute(new RunnableTask());

    e.submit(new CallableTask());

    e.shutdown();

    node.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:20,

    示例18: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    Config config = new Config();

    config.useClusterServers()

    .addNodeAddress("127.0.0.1:7001", "127.0.0.1:7002", "127.0.0.1:7003");

    RedissonClient redisson = Redisson.create(config);

    RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);

    nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor", 5));

    RedissonNode node = RedissonNode.create(nodeConfig);

    node.start();

    RScheduledExecutorService e = redisson.getExecutorService("myExecutor");

    e.schedule(new RunnableTask(), 10, TimeUnit.SECONDS);

    e.schedule(new CallableTask(), 4, TimeUnit.MINUTES);

    e.schedule(new RunnableTask(), CronSchedule.of("10 0/5 * * * ?"));

    e.schedule(new RunnableTask(), CronSchedule.dailyAtHourAndMinute(10, 5));

    e.schedule(new RunnableTask(), CronSchedule.weeklyOnDayAndHourAndMinute(12, 4, Calendar.MONDAY, Calendar.FRIDAY));

    e.shutdown();

    node.shutdown();

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:24,

    示例19: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) {

    // connects to 127.0.0.1:6379 by default

    RedissonClient server = Redisson.create();

    RedissonClient client = Redisson.create();

    try {

    server.getRemoteService().register(RemoteInterface.class, new RemoteImpl());

    RemoteInterface service = client.getRemoteService().get(RemoteInterface.class);

    service.myMethod(21L);

    } finally {

    client.shutdown();

    server.shutdown();

    }

    }

    开发者ID:redisson,项目名称:redisson-examples,代码行数:18,

    示例20: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(final String[] args) {

    final Config config = new Config();

    config.useSingleServer()

    .setAddress("redis-14926.c10.us-east-1-3.ec2.cloud.redislabs.com:14926")

    .setConnectionMinimumIdleSize(1)

    .setConnectionPoolSize(2);

    final RedissonClient client = Redisson.create(config);

    try {

    final RemoteInterface service = client.getRemoteService().get(RemoteInterface.class);

    final long result = service.myMethod(21L);

    System.out.println("result = " + result);

    } finally {

    client.shutdown();

    }

    }

    开发者ID:KleeGroup,项目名称:vertigo-labs,代码行数:20,

    示例21: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(final String[] args) {

    final Config config = new Config();

    config.useSingleServer()

    .setAddress("redis-14926.c10.us-east-1-3.ec2.cloud.redislabs.com:14926")

    .setConnectionMinimumIdleSize(1)

    .setConnectionPoolSize(2);

    // connects to 127.0.0.1:6379 by default

    final RedissonClient server = Redisson.create(config);

    final RedissonClient client = Redisson.create(config);

    try {

    server.getRemoteService().register(RemoteInterface.class, new RemoteImpl());

    final RemoteInterface service = client.getRemoteService().get(RemoteInterface.class);

    final long result = service.myMethod(21L);

    System.out.println("result = " + result);

    } finally {

    client.shutdown();

    server.shutdown();

    }

    }

    开发者ID:KleeGroup,项目名称:vertigo-labs,代码行数:24,

    示例22: main

    ​点赞 3

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(final String[] args) throws InterruptedException, ExecutionException {

    final Config config = new Config();

    config.useSingleServer()

    .setAddress("redis-14926.c10.us-east-1-3.ec2.cloud.redislabs.com:14926")

    .setConnectionMinimumIdleSize(1)

    .setConnectionPoolSize(2);

    final RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);

    nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor", 1));

    final RedissonNode node = RedissonNode.create(nodeConfig);

    node.start();

    final RedissonClient client = Redisson.create(config);

    final RExecutorService e = client.getExecutorService("myExecutor");

    System.out.println("executorService.isShutdown :" + e.isShutdown());

    System.out.println("executorService.isTerminated :" + e.isTerminated());

    //e.execute(new RunnableTask());

    final Future result = e.submit(new CallableTask());

    System.out.println("result =" + result.get());

    e.shutdown();

    node.shutdown();

    }

    开发者ID:KleeGroup,项目名称:vertigo-labs,代码行数:24,

    示例23: redissonClient

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    @Bean

    public RedissonClient redissonClient() {

    Client client = new Client();

    String nodes = PropertiesUtil.getString("redis.cluster.nodes");

    if (StringUtils.isNotBlank(nodes)) {

    client.setNodeAddresses(nodes);

    } else {

    String address = "redis://" + PropertiesUtil.getString("redis.host") + ":"

    + PropertiesUtil.getString("redis.port");

    client.setAddress(address);

    }

    client.setPassword(PropertiesUtil.getString("redis.password"));

    client.setTimeout(PropertiesUtil.getInt("redis.timeout"));

    return client.getRedissonClient();

    }

    开发者ID:iBase4J,项目名称:iBase4J-Common,代码行数:16,

    示例24: getRedis

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    private RedissonClient getRedis() {

    if (redisTemplate == null) {

    synchronized (RedissonHelper.class) {

    if (redisTemplate == null) {

    redisTemplate = applicationContext.getBean(RedissonClient.class);

    }

    }

    }

    return redisTemplate;

    }

    开发者ID:guokezheng,项目名称:automat,代码行数:11,

    示例25: mapsLocalCache

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    @Test

    void mapsLocalCache() {

    Config config = new Config();

    config.useSingleServer().setAddress("http://127.0.0.1:6379");

    RedissonClient client = Redisson.create(config);

    LocalCachedMapOptions options = LocalCachedMapOptions.defaults().maxIdle(5 * 1000).timeToLive(5 * 1000);

    RLocalCachedMap map = client.getLocalCachedMap("myMap", options);

    Waiter waiter = new Waiter();

    map.put("key", 20);

    new Thread(() -> {

    mapsLocalCache2(waiter);

    waiter.resume();

    }).start();

    try {

    Thread.sleep(1000);

    }

    catch(InterruptedException e) {

    e.printStackTrace();

    }

    System.out.println("SET");

    map.put("key", 25);

    try {

    waiter.await();

    }

    catch(Throwable throwable) {

    throwable.printStackTrace();

    }

    }

    开发者ID:Superioz,项目名称:MooProject,代码行数:34,

    示例26: mapsItemChange

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    @Test

    void mapsItemChange() {

    Config config = new Config();

    config.useSingleServer().setAddress("http://127.0.0.1:6379");

    RedissonClient client = Redisson.create(config);

    LocalCachedMapOptions options = LocalCachedMapOptions.defaults().maxIdle(5 * 1000).timeToLive(5 * 1000);

    RLocalCachedMap> map = client.getLocalCachedMap("myMap", options);

    FinalValue value = new FinalValue(15);

    map.put("test", value);

    Waiter waiter = new Waiter();

    System.out.println("Value: " + value.get());

    new Thread(() -> {

    mapsItemChange2(waiter);

    waiter.resume();

    }).start();

    try {

    Thread.sleep(1000);

    }

    catch(InterruptedException e) {

    e.printStackTrace();

    }

    value.set(18);

    map.put("test", value);

    System.out.println("VALUE SET.");

    try {

    waiter.await();

    }

    catch(Throwable throwable) {

    throwable.printStackTrace();

    }

    }

    开发者ID:Superioz,项目名称:MooProject,代码行数:38,

    示例27: getStorage

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public RedissonClient getStorage() {

    if (storage == null) {

    Iterator it = serviceLoader.iterator();

    if (it.hasNext()) {

    this.storage = it.next();

    } else {

    throw new NoSuchElementException();

    }

    }

    return storage;

    }

    开发者ID:JungleTree,项目名称:JungleTree,代码行数:12,

    示例28: NFFTRedisStorage

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public NFFTRedisStorage() {

    Config config = new Config();

    config.useSingleServer().setAddress("127.0.0.1:6379");

    //config.useSingleServer().setAddress("157.193.92.74:6379");

    final RedissonClient redisson = Redisson.create(config);

    fingerprintMap = redisson.getMap("integerMap");

    metaDataMap = redisson.getMap("descriptionMap");

    secondsStored = redisson.getAtomicLong("secondsStoredAtomicLong");

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){

    @Override

    public void run() {

    redisson.shutdown();

    }}));

    //rnd = new Random();

    }

    开发者ID:JorenSix,项目名称:Panako,代码行数:20,

    示例29: SitemapController

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    /**

    * Instantiates a new Sitemap controller.

    *

    * @param sitemapGenerator the sitemap generator

    * @param redissonClient the redisson client

    */

    @Autowired

    public SitemapController(final SitemapGenerator sitemapGenerator,

    final RedissonClient redissonClient) {

    this.sitemapGenerator = sitemapGenerator;

    this.redissonClient = redissonClient;

    }

    开发者ID:mhaddon,项目名称:Sound.je,代码行数:13,

    示例30: EventServiceImpl

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    /**

    * Instantiates a new Event service.

    *

    * @param eventRepository the event repository

    * @param redissonClient

    */

    @Autowired

    EventServiceImpl(final EventRepository eventRepository,

    final RedissonClient redissonClient,

    final OccurrenceService occurrenceService) {

    this.eventRepository = eventRepository;

    this.redissonClient = redissonClient;

    this.occurrenceService = occurrenceService;

    }

    开发者ID:mhaddon,项目名称:Sound.je,代码行数:15,

    示例31: MediumController

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    /**

    * Instantiates a new Medium controller.

    *

    * @param redissonClient the redisson client

    * @param mediumRepository the medium repository

    * @param mediumService the medium service

    * @param mediumParser the medium parser

    */

    @Autowired

    MediumController(final RedissonClient redissonClient,

    final MediumRepository mediumRepository,

    final MediumService mediumService,

    final MediumParser mediumParser) {

    this.redissonClient = redissonClient;

    this.mediumRepository = mediumRepository;

    this.mediumService = mediumService;

    this.mediumParser = mediumParser;

    }

    开发者ID:mhaddon,项目名称:Sound.je,代码行数:19,

    示例32: LoginAttemptService

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    /**

    * Instantiates a new Login attempt service.

    *

    * @param redissonClient the redisson client

    * @param loginConfigSettings the login settings

    */

    @Autowired

    public LoginAttemptService(final RedissonClient redissonClient,

    final LoginConfigSettings loginConfigSettings) {

    this.redissonClient = redissonClient;

    this.loginConfigSettings = loginConfigSettings;

    }

    开发者ID:mhaddon,项目名称:Sound.je,代码行数:13,

    示例33: getRedis

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    private RedissonClient getRedis() {

    if (redisTemplate == null) {

    synchronized (RedissonHelper.class) {

    if (redisTemplate == null) {

    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();

    redisTemplate = wac.getBean(Redisson.class);

    }

    }

    }

    return redisTemplate;

    }

    开发者ID:tb544731152,项目名称:iBase4J,代码行数:12,

    示例34: getRedis

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    private RedissonClient getRedis() {

    if (redisTemplate == null) {

    synchronized (RedissonCacher.class) {

    if (redisTemplate == null) {

    redisTemplate = applicationContext.getBean(RedissonClient.class);

    }

    }

    }

    return redisTemplate;

    }

    开发者ID:liuxx001,项目名称:bird-java,代码行数:11,

    示例35: redisson

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    /**

    * redisson文档

    *

    * @return

    * @throws IOException

    */

    @Bean( destroyMethod = "shutdown" )

    public RedissonClient redisson () throws IOException {

    Config config = new Config();

    config.useSingleServer()

    .setAddress( this.getRedissonAddress( host , port ) )

    .setPassword( password )

    .setDatabase( database );

    return Redisson.create( config );

    }

    开发者ID:yujunhao8831,项目名称:spring-boot-start-current,代码行数:16,

    示例36: main

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Bench bench = new RedissonBench() {

    @Override

    public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,

    MetricRegistry metrics) {

    RAtomicLong atomic = benchInstance.getAtomicLong("incr_" + threadNumber + "_" + iteration);

    Timer.Context time = metrics.timer("list").time();

    atomic.incrementAndGet();

    time.stop();

    }

    };

    Benchmark benchmark = new Benchmark(bench);

    benchmark.run(args);

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:16,

    示例37: main

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Bench bench = new RedissonBench() {

    @Override

    public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,

    MetricRegistry metrics) {

    RBucket bucket = benchInstance.getBucket("bucket_" + threadNumber + "_" + iteration);

    Timer.Context time = metrics.timer("bucket").time();

    bucket.set(data);

    time.stop();

    }

    };

    Benchmark benchmark = new Benchmark(bench);

    benchmark.run(args);

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:16,

    示例38: main

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Bench bench = new RedissonBench() {

    @Override

    public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,

    MetricRegistry metrics) {

    RMap map = benchInstance.getMap("map_" + threadNumber);

    Timer.Context time = metrics.timer("map").time();

    map.put(data, data);

    time.stop();

    }

    };

    Benchmark benchmark = new Benchmark(bench);

    benchmark.run(args);

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:16,

    示例39: main

    ​点赞 2

    import org.redisson.api.RedissonClient; //导入依赖的package包/类

    public static void main(String[] args) throws InterruptedException {

    Bench bench = new RedissonBench() {

    @Override

    public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,

    MetricRegistry metrics) {

    RBucket bucket = benchInstance.getBucket("bucket_" + threadNumber + "_" + iteration);

    Timer.Context time = metrics.timer("bucket").time();

    bucket.set(value);

    time.stop();

    }

    };

    Benchmark benchmark = new Benchmark(bench);

    benchmark.run(args);

    }

    开发者ID:redisson,项目名称:redisson-benchmark,代码行数:16,

    注:本文中的org.redisson.api.RedissonClient类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

    展开全文
  • private final RedissonClient redissonClient; public void outerFactoryHelper(SeekcyLocationResult result) { String lockName = ""; RLock lock = redissonClient.getLock(lockName); try { b.
    import org.redisson.api.RedissonClient;
    
    @Service
    @Slf4j
    @RequiredArgsConstructor(onConstructor = @__(@Autowired))
    
    class ClassName{
        private final RedissonClient redissonClient;
    	public void outerFactoryHelper(SeekcyLocationResult result) {
    		String lockName = "lock_name";
    		RLock lock = redissonClient.getLock(lockName);
    		try {
    			boolean isLock = lock.tryLock(5000, 5000, TimeUnit.MILLISECONDS);
    			if(!isLock){
    				log.warn("outerFactoryHelper lock failed!!!");
    				return;
    			}
    
    
    
    			// 业务代码
                ......
                
    
    
    		} catch (InterruptedException e) {
    			log.info("outerFactoryHelper lock exception!!!");
    		} finally {
    			if(lock.isLocked()){
    				lock.unlock();
    			}
    		}
    
    	}
    
    
    }

     

    展开全文
  • 分布式Redis锁 - RedissonClient

    千次阅读 2019-10-18 17:05:59
    Redis Java Client选型-Jedis Lettuce Redisson 可重入锁(Reentrant Lock) 先写个单元测试试一下 ... private RedissonClient redissonClient; //请求的key private static final String demo ...
    Redis Java Client选型-Jedis Lettuce Redisson
    最常用的可重入锁(Reentrant Lock) 先写个单元测试试一下
    public class RedisLockTest {
    
        private RedissonClient redissonClient;
    
        //请求的key
        private static final String demo ="u001";
    
        //模拟短时间内的并发请求量
    
        private static final int threadNum =5;
    
        @Before
        public void init(){
            Config config = new Config();
            config.useSingleServer().setAddress("redis://120.78.144.70:6379");
            this.redissonClient = Redisson.create(config);
    
            System.out.println(Thread.currentThread().getName()+"是否存在key"+redissonClient.getLock(demo).isExists());
        }
    
        private class UserRequest implements Runnable{
    
            private CountDownLatch cdl;
    
            public UserRequest(CountDownLatch latch){
                this.cdl=latch;
            }
    
            @Override
            public void run() {
                try {
                    if (redissonClient.getLock(demo).tryLock(0L,-1L, TimeUnit.SECONDS)) {
                        System.out.println(Thread.currentThread().getName()+"获取锁成功");
                        Thread.sleep(5000);
                        redissonClient.getLock(demo).unlock();
                        System.out.println(Thread.currentThread().getName()+"释放锁成功");
                    }else{
                        System.out.println(Thread.currentThread().getName()+"获取锁失败"+"是否存在key"+redissonClient.getLock(demo).isExists());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    //倒计时计数一次
                    cdl.countDown();
                }
            }
        }
    
        @Test
        public void testRedissonLock(){
            CountDownLatch cdl=new CountDownLatch(threadNum);
            Executor executor = Executors.newFixedThreadPool(threadNum);
            try{
                for (int i =0; i< threadNum; i++) {
                    if(i==2){
                        //模拟在业务代码没执行完毕时另一个线程获取锁
                        Thread.sleep(1500);
                    }
                    executor.execute(new UserRequest(cdl));
                }
                //阻塞主线程,等待所有的子线程执行完毕
                cdl.await();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    

    分布式锁的实现分析参考
    https://www.jianshu.com/p/a8b3473f9c24

    比较关注的一个参数一个是过期时间,一个是定时续约过期时间

    通过阅读源码知道lesstime参数决定是否续约

        private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {
            if (leaseTime != -1L) {
                return this.tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
            } else {
                RFuture<Long> ttlRemainingFuture = this.tryLockInnerAsync(this.commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
                ttlRemainingFuture.addListener(new FutureListener<Long>() {
                    public void operationComplete(Future<Long> future) throws Exception {
                        if (future.isSuccess()) {
                            Long ttlRemaining = (Long)future.getNow();
                            if (ttlRemaining == null) {
                                RedissonLock.this.scheduleExpirationRenewal(threadId);
                            }
    
                        }
                    }
                });
                return ttlRemainingFuture;
            }
        }
    

    总结一点

    if(leaseTime==-1L){
        开启自动续期的定时任务,不断重置过期时间为lockWatchdogTimeout
        定时任务的频率为lockWatchdogTimeout配置时间的1/3
    }else{
        不自动续期
        设置过期时间为leaseTime
    }
    

    所有属性介绍 https://yq.aliyun.com/articles/551640/

    其他锁类型的锁参考
    (联锁,红锁,读写锁,信号量,可过期性信号量)
    https://blog.csdn.net/l1028386804/article/details/73523810

    展开全文
  • 最近在使用 Redisson,但是发现 RedissonClient.shutdown() 有点问题,类似下面的代码RedissonClient redisson = Redisson.create();redisson.shutdown();在我这里居然报错类似下面这样18:41:26.880 [redisson-netty...
  • RedissonClient中提供了好多种锁,还有其它很多实用的方法。Redisson是Redis官方推荐的Java版的Redis客户端。实现了RedissonClient的接口。这里只介绍其中的锁。
  • packagecom.montnets.ums.msgroute.redis;importlombok.extern.slf4j.Slf4j;importorg.redisson.api....importorg.redisson.api.RedissonClient;importorg.springframework.beans.factory.annotation.Autowired;i...
  • Error creating bean with name 'redissonClient': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [...
  • @Autowired RedisProperties redisProperties; /** * 哨兵模式自动装配 * * @return */ @Bean(destroyMethod = "shutdown") @ConditionalOnProperty(name="spring.redis... public RedissonClient redisson...
  • 需要引入redissonClient依赖 存储缓存部分: @Autowired RedissonCilent redisson; //创建一个map并写入数据 RBatch rbatch = redisson.createBatch(BatchOptions.defaults()); RMapAsync<K, V> map = ...
  • RLock lock = redissonClient.getLock("KEY"); if (lock.isLocked()) { return "您已有任务正在进行中!请稍后再用!"; } //加锁 lock.lock(10, TimeUnit.MINUTES); 查询redis服务器后: get ...
  • redis反序列化失败(RedissonClient)错误redis反序列化失败解决方法 错误 com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxxxxxx` (no Creators, like default ...
  • /** * redisson操作类 * @author 朱友德 */ @Service("redissonService") public class RedissonService { @Autowired private RedissonClient redissonClient; public void getRedissonClient() throws IOException...
  • 解决Redisson出现Failed to instantiate [org.redisson.api.RedissonClient]: Factory method 'create' threw exception; nested exception is java.lang.ArrayIndexOutOfBoundsException: 0的问题 .....
  • RedissonClient redisson = Redisson.create(config); 调用Config.toJSON方法可以将一个Config配置实例序列化为一个含有JSON数据类型的字符串: Config config = new Config(); // ... 省略许多其他的设置 String ...
  • RedissonClient RedissonClient redisson = Redisson.create(config); Spring方式 address=“127.0.0.1:6379" /> HelloWorld 3 验证是否成功 redisson.getConfig().toJSON().toString() 结果 {"singleServerConfig...
  •  最近项目中使用了redisson的哨兵模式来作为redis操作的客户端,然后一个意外出现了,启动报:Failed to instantiate [org.redisson.api.RedissonClient]: Factory method 'create' threw exception; nested ...
  • 以下是关于使用RAtomicLong对象的范例: RedissonClient client = Redisson.create(config); RAtomicLong longObject = client.getAtomicLong('myLong'); // 同步执行方式 longObject.compareAndSet(3, 401); // ...
  • 第三方框架整合 1 Redisson提供了和Spring框架的各项特性类似的,以Spring XML的命名空间的方式配置RedissonClient实例和它所支持的所有对象和服务; 2 Redisson完整的实现了Spring框架里的缓存机制; 3 Redisson...
  • import org.redisson.api.RedissonClient; import org.redisson.config.Config; /** * 程序化配置方法 */ public class FirstApp { public static void main(String args[]) throws IOException { ...
  • 1.流程逻辑-创建key-过期时间,获取key值超过一定限制进行异常返回,否在正常访问,并且自增key值 // @Test public void limitQuery() throws InterruptedException { for (int i = 0; i <...
  • 创建RedissonClient对象实例的方式多钟多样,可以直接通过在代码中设置Redis服务的相关参数创建,也可以通过加载JSON格式或YAML格式配置文件创建,还可以通过在Spring XML文件中使用Redisson标签配置创建,具体如何...
  • 错误描述: 在spring boot中加入redisson创建客户端对象后,成功运行,但是在对接口访问时,报错: org.redisson.client.RedisAuthRequiredException: NOAUTH Authentication required.. 解决方法: ...
  • KEYSRKeys.findKeysByPattern() RKeys.findKeysByPatternAsync() RKeysReactive.findKeysByPattern() RedissonClient.findBuckets() LINDEXRList.get() RList.getAsync() RListReactive.get() LLENRList.size() R...
  • 源码解释: org.redisson.RedissonLock#tryAcquireOnceAsync private RFuture<Boolean> tryAcquireOnceAsync(long leaseTime, TimeUnit unit, final long threadId) { if (leaseTime !...
  • 注入redisTemplate @Autowired private RedisTemplate<String,String> redisTemplate; 1 保存和读取Set SetOperations<String, String> set = redisTemplate.opsForSet();... set.ad...

空空如也

空空如也

1 2 3 4 5 ... 10
收藏数 190
精华内容 76
关键字:

redissonclient

redis 订阅