redis api示例

redis使用

package org.arrow.redis.test;

import com.google.common.collect.Sets;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import redis.clients.jedis.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by root on 2016/7/6.
 */
public class JedisTest {

    public static void main(String[] args) throws IOException {
        // 集群中的任意节点,不管主从都可以执行常规的操作
        Set<HostAndPort> hostPorts = Sets.newHashSet();

        Set<String> strs = Sets.newHashSet();

        Set<String> strings = Sets.newHashSet();

        hostPorts.add(new HostAndPort("192.168.2.45", 6379));
        hostPorts.add(new HostAndPort("192.168.2.46", 6379));
        hostPorts.add(new HostAndPort("192.168.2.47", 6379));
        hostPorts.add(new HostAndPort("192.168.2.45", 6380));
        hostPorts.add(new HostAndPort("192.168.2.46", 6380));
        hostPorts.add(new HostAndPort("192.168.2.47", 6380));

        final JedisCluster redisCluster = new JedisCluster(hostPorts);

        Map<String, JedisPool> nodes = redisCluster.getClusterNodes();

        // 集群node信息
        Iterator<Map.Entry<String, JedisPool>> iterNodes = nodes.entrySet().iterator();
        while (iterNodes.hasNext()) {
            Map.Entry<String, JedisPool> entry = iterNodes.next();
            Jedis jedis = entry.getValue().getResource();
            System.out.println(entry.getKey());
        }

        redisCluster.set("foo", "bar");

        // 直接覆盖原来的数据
        redisCluster.set("foo", "1234567jtt");
        System.out.println(redisCluster.get("foo"));

        // 左侧入队
        for (int i = 0; i < 100; i++) {
            redisCluster.rpush("mylist", "e-" + i);
        }

        // 右侧出队
        for (int i = 0; i < 30; i++) {
            String str = redisCluster.lpop("mylist");
        }

        // 返回所有的,但不会清空队列
        List<String> userList = redisCluster.lrange("mylist", 0, -1);
        System.out.println(userList);

        for (int i = 0; i < 30; i++) {
            String str = redisCluster.lpop("mylist");
        }

        // 返回队列长度
        Long length = redisCluster.llen("mylist");
        System.out.println("length = " + length);

        // 排序
        System.out.println(redisCluster.lrange("mylist", 0, 3));
        // 修改列表中单个值
        redisCluster.lset("mylist", 0, "hello list!");
        // 获取列表指定下标的值
        System.out.println(redisCluster.lindex("mylist", 1));
        // 删除列表指定下标的值
        System.out.println(redisCluster.lrem("mylist", 1, "vector"));

        // 删除的对象数,返回1
        Long s = redisCluster.del("mylist");
        System.out.println("deleted  = " + s);

        // 集群环境下mset会有问题  No way to dispatch this command to Redis Cluster because keys have different slots.
//        redisCluster.mset("id", "123", "name" , "myname");
//        System.out.println(redisCluster.mget("id"));

        // 相关于echo命令
        System.out.println(redisCluster.echo("abcdddd"));

        // 判断key是否存在
        System.out.println(redisCluster.exists("foo"));

        // 追加数据
        redisCluster.append("foo", "append hello, world");
        System.out.println(redisCluster.get("foo"));

        // setex 设置过期时间,2秒
        redisCluster.setex("foo1", 2, "foo is exp!");
        System.out.println(redisCluster.get("foo1"));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
        }
        System.out.println(redisCluster.get("foo1")); // 这时候已经过期返回null

        // 截取返回值,前三位
        System.out.println(redisCluster.getrange("foo", 0, 3));


        redisCluster.zadd("zhongsou:hackers", 1940, "Alan Kay");
        redisCluster.zadd("zhongsou:hackers", 1953, "Richard Stallman");
        redisCluster.zadd("zhongsou:hackers", 1943, "Jay");
        redisCluster.zadd("zhongsou:hackers", 1920, "Jellon");
        redisCluster.zadd("zhongsou:hackers", 1965, "Yukihiro Matsumoto");
        redisCluster.zadd("zhongsou:hackers", 1916, "Claude Shannon");
        redisCluster.zadd("zhongsou:hackers", 1969, "Linus Torvalds");
        redisCluster.zadd("zhongsou:hackers", 1912, "Alan Turing");
        Set<String> hackers = redisCluster.zrange("zhongsou:hackers", 0, -1);
        System.out.println(hackers);

        Set<String> hackers2 = redisCluster.zrevrange("zhongsou:hackers", 0, -1);
        System.out.println(hackers2);

        // 区间操作,我们请求Redis返回score介于负无穷到1920年之间的元素(两个极值也包含了)。
        Set<String> hackers3 = redisCluster.zrangeByScore("zhongsou:hackers", "-inf", "1920");
        System.out.println(hackers3);


        try {
            ExecutorService service = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 10; i++) {
                final int kkk = i;
                final Sub sub = new Sub("id:" + i);
                service.submit(new Runnable() {
                    @Override
                    public void run() {
                        // 接受哪个channel的信号
                        redisCluster.psubscribe(sub, "mychannel", "mychannel" + kkk);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 三个部分随机发
        ExecutorService service = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 3; i++) {
            final int kkk = i;
            service.submit(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        // 派发信息
                        redisCluster.publish("mychannel" + kkk, "msg-" + new Random().nextInt(10));
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        System.in.read();
    }
}

/**
 * 订阅者
 */
final class Sub extends JedisPubSub {
        private String name;

        public Sub(String name){
            this.name = name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void onMessage(String channel, String message) {
            System.out.println(name + " from channel = " + channel + ", message = " + message);
        }

        public void onPMessage(String pattern, String channel, String message) {
        }

        public void onSubscribe(String channel, int subscribedChannels) {
        }

        public void onUnsubscribe(String channel, int subscribedChannels) {
        }

        public void onPUnsubscribe(String pattern, int subscribedChannels) {
        }

        public void onPSubscribe(String pattern, int subscribedChannels) {
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值