Redis简单入门

Redis安装

下载地址:传送门 下载安装后解压即可

  • 运行
  1. win + R 打开cmd
  2. cd E:\apps\redis(你的redis路径)
  3. 执行:redis-server.exe redis.windows.config
  • 存键值对

redis-cli.exe -h 127.0.0.1 -p 6379
set [key] [value]

  • 取键值对

get [key]

  • java使用redis需要驱动包jedis.jar 传送门

Redis 字符串 String

详细参考传送门

/**
 * Redis 字符串(String)
 */
public static void redisStringTest(Jedis jedis) {
    String key = "test";
    setData(jedis, "test", "这是一个测试数据");
    getData(jedis, "test");
    getData(jedis, "test1");

    // 判断是否存在key EXISTS KEY
    Boolean isExit = jedis.exists(key);
    System.out.println("是否存在" + key + ":" + String.valueOf(isExit));

    // 给定过期时间 EXPIRE KEY SECONDS
    jedis.expire(key, 520);
    // 判断key剩余过期时间 (毫秒)
    Long expireTimePTTL = jedis.pttl(key);
    System.out.println(key + "的剩余过期时间是" + expireTimePTTL + "毫秒");
    // 判断key剩余过期时间 (秒)
    Long expireTimeTTL = jedis.ttl(key);
    System.out.println(key + "的剩余过期时间是" + expireTimeTTL + "秒");
    // 修改key
    jedis.rename(key, "newName1");
    getData(jedis, "newName1");
    // 删除key
    jedis.del("newName1");
    getData(jedis, "newName1");
}

    /**
     * 存储数据 (String)
     *
     * @param jedis
     * @param key
     * @param value
     */
    public static void setData(Jedis jedis, String key, String value) {
        jedis.set(key, value);
    }

    /**
     * 读取数据 (String)
     *
     * @param jedis
     * @param key
     */
    public static void getData(Jedis jedis, String key) {
        if (jedis.get(key) == null) {
            System.out.println("没有" + key + "相关数据");
        } else {
            System.out.println(key + "的值为:" + jedis.get(key));
        }
    }

Redis 哈希 Hash

详细参考传送门

/**
     * Redis 哈希(Hash)
     */
    public static void redisHashTest(Jedis jedis) {
        String hKey = "hashTest";
        Map<String, String> map = new HashMap<>();
        map.put("nameCN", "杨凡");
        map.put("nameEN", "hermit");
        map.put("sex", "boy");
        map.put("age", "25");
        map.put("birth", "1997-09-18");
        jedis.hmset(hKey, map);

        // 查看是否存在key
        System.out.println("-------查看是否存在key-------");
        Boolean isHExists = jedis.hexists(hKey, "nameCN");
        System.out.println("是否存在" + hKey + ":" + String.valueOf(isHExists));

        // 获取指定字段值
        System.out.println("-------获取指定字段值-------");
        String nameCN = jedis.hget(hKey, "nameCN");
        System.out.println(hKey + "中的nameCN值为:" + nameCN);

        // 获取所有字段值
        System.out.println("-------获取所有字段值-------");
        Map<String, String> map1 = jedis.hgetAll(hKey);
        // 遍历map1
        for (String key : map1.keySet()) {
            System.out.println("key:" + key + " " + "Value:" + map1.get(key));
        }

        // 获取所有hash中的字段
        System.out.println("-------获取所有hash中的key-------");
        Set<String> keySet = jedis.hkeys(hKey);
        String allKeyStr = "";
        for (String key : keySet) {
            allKeyStr += key + ",";
        }
        System.out.println("所有的key值为:" + allKeyStr);

        // 获取hash表中字段的数量
        System.out.println("-------获取hash表中字段的数量-------");
        Long num = jedis.hlen(hKey);
        System.out.println("key字段的数量为:" + num);

        // 修改hash字段值
        System.out.println("-------修改hash字段值-------");
        jedis.hset(hKey, "nameCN", "杨凡凡");
        System.out.println(jedis.hmget(hKey, "nameCN"));

        // 获取hash中所有值
        System.out.println("-------获取hash中所有值-------");
        List<String> valueSet = jedis.hvals(hKey);
        String valueListStr = "";
        for (String valueStr : valueSet) {
            valueListStr += valueStr + ",";
        }
        System.out.println("hash所有值为:" + valueListStr);
    }

Redis 列表 List

详细参考传送门

    /**
     * Redis 列表(List)
     */
    public static void redisListTest(Jedis jedis) {
        String lKey = "listKeyTest";
        if (jedis.llen(lKey) <= 0) {
            jedis.lpush(lKey, "sunday is coming i wanna drive my car");
            jedis.lpush(lKey, "to your apartment with a parent like a star");
            jedis.lpush(lKey, "forecast say the weather may be running hard");
            jedis.lpush(lKey, "but i know the sun will shine for us");
        }
        // 获取第一个元素
        System.out.println("-------获取第一个元素(移除)-------");
        String lpop = jedis.lpop(lKey);
        System.out.println("第一个元素:" + lpop);
        // 获取最后一个元素
        System.out.println("-------获取最后一个元素(移除了)-------");
        String rpop = jedis.rpop(lKey);
        System.out.println("最后一个元素:" + rpop);
        // 插入
//        jedis.linsert(lKey, BinaryClient.LIST_POSITION.BEFORE, "sunday is coming i wanna drive my car", "young for you");

        // 获取列表长度
        Long num = jedis.llen(lKey);
        System.out.println("列表的长度为:" + num);
    }

集合 Set

详细参考传送门

有序集合 sorted Set

详细参考传送门

HyperLogLog

详细参考传送门

发布订阅

详细参考传送门

我编写了一个简单的发布者-订阅者功能,供参考
1个发布者,3个订阅者 控台输入流接受发布消息,输入T1,T2,T3可取消订阅,D1,D2,D3可订阅

代码如下

  1. 创建发布者
/**
 * 发布者
 */
public class Publisher extends Thread {

    public Jedis jedisP;
    public Jedis jedisS1;
    public Jedis jedisS2;
    public Jedis jedisS3;
    SubThread subThread1;
    SubThread subThread2;
    SubThread subThread3;
    private final String channel = "mychannel";

    public Publisher() {
        jedisP = new Jedis("127.0.0.1", 6379);
        jedisS1 = new Jedis("127.0.0.1", 6379);
        jedisS2 = new Jedis("127.0.0.1", 6379);
        jedisS3 = new Jedis("127.0.0.1", 6379);
        subThread1 = new SubThread(jedisS1, "中国");
        subThread2 = new SubThread(jedisS2, "美国");
        subThread3 = new SubThread(jedisS3, "日本");
    }

    SubThread subThread = new SubThread();
    private Jedis jedis;

    public Publisher(Jedis jedis) {
        this.jedis = jedis;
        jedisP = new Jedis("127.0.0.1", 6379);
        jedisS1 = new Jedis("127.0.0.1", 6379);
        jedisS2 = new Jedis("127.0.0.1", 6379);
        jedisS3 = new Jedis("127.0.0.1", 6379);
        subThread1 = new SubThread(jedisS1, "中国");
        subThread2 = new SubThread(jedisS2, "美国");
        subThread3 = new SubThread(jedisS3, "日本");
    }

    @Override
    public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            String line = null;
            try {
                line = reader.readLine();
                if ("quit".equals(line)) {
                    break;
                } else if ("D1".equals(line)) {
                    try{
                        jedisS1.subscribe(subThread1.subscriber, channel);
                    } catch (Exception e) {
                        System.out.println(String.format("操作:订阅失败, %s", e));
                    } finally {
                        if (jedisS1 != null) {
                            jedisS1.close();
                        }
                    }
                } else if ("D2".equals(line)) {
                    jedisS2.subscribe(subThread2.subscriber, channel);
                } else if ("D3".equals(line)) {
                    jedisS3.subscribe(subThread3.subscriber, channel);
                } else if ("T1".equals(line)) {
                    subThread1.subscriber.unsubscribe(channel);
                } else if ("T2".equals(line)) {
                    subThread2.subscriber.unsubscribe(channel);
                } else if ("T3".equals(line)) {
                    subThread3.subscriber.unsubscribe(channel);
                } else {
                    jedis.publish("mychannel", line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
  1. 创建订阅者
/**
 * 订阅者一
 */
public class Subscriber extends JedisPubSub {
    private String name;
    public Subscriber(String name) {
        this.name = name;
    }

    // 收到消息后调用
    @Override
    public void onMessage(String channel, String message) {
        System.out.println(String.format("订阅者 %s:接受消息:, 频道: %s, 消息: %s", name, channel, message));
    }

    // 订阅了频道会调用
    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println(String.format("订阅者 %s:订阅频道:, 频道: %s, 已订阅:  %d", name, channel, subscribedChannels));
    }

    // 取消订阅会调用
    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        System.out.println(String.format("订阅者 %s:取消订阅, 频道: %s, 已订阅: %d", name, channel, subscribedChannels));
    }
}

3.订阅者订阅

/**
 * 订阅操作
 */
public class SubThread extends Thread{
    private Jedis jedis;
    private String name;
    public Subscriber subscriber;

    private final String channel = "mychannel";

    public SubThread() {

    }
    public SubThread(Jedis jedis, String name) {
        super("SubThread");
        this.jedis = jedis;
        this.name = name;
        subscriber = new Subscriber(name);
    }

    @Override
    public void run() {
        System.out.println(String.format("订阅 redis, 频道 %s, 线程将被阻止", channel));
        try{
            jedis.subscribe(subscriber, channel);
        } catch (Exception e) {
            System.out.println(String.format("操作:订阅失败, %s", e));
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
  1. 测试
/**
 * 测试类
 */
public class PubSubDemo {

    public static void main(String args[]) {
        Publisher publisher1 = new Publisher();
        Jedis jedisP = publisher1.jedisP;
        Jedis jedisS1 = publisher1.jedisS1;
        Jedis jedisS2 = publisher1.jedisS2;
        Jedis jedisS3 = publisher1.jedisS3;

        // 连接redis服务端
        System.out.println(String.format("测试类:redis启动成功. redis的ip为: %s, redis端口为: %d", "127.0.0.1", 6379));

        // 订阅者
        SubThread subThread1 = publisher1.subThread1;
        SubThread subThread2 = publisher1.subThread2;
        SubThread subThread3 = publisher1.subThread3;
        subThread1.start();
        subThread2.start();
        subThread3.start();

        // 发布者
        Publisher publisher = new Publisher(jedisP);
        publisher.start();
    }
}

事务

详细参考传送门

public static void main(String args[]) {
        // 连接本地Redis服务
        Jedis jedis = new Jedis("localhost");

        Transaction transaction = jedis.multi();
        transaction.append("name", "yangfan");
        transaction.append("age", "18");
        transaction.append("sex", "boy");
		// 此处代码会报错,因为还没有存入键值对
//        System.out.println("-----------exec前-------------");
//        System.out.println(jedis.get("name"));
//        System.out.println(jedis.get("age"));
//        System.out.println(jedis.get("sex"));

        transaction.exec();

        System.out.println("-----------exec后-------------");
        System.out.println(jedis.get("name"));
        System.out.println(jedis.get("age"));
        System.out.println(jedis.get("sex"));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜狼狼与灰太杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值