0
点赞
收藏
分享

微信扫一扫

【Redis】6、Java操作Redis —— Jedis

醉倾城1 2022-03-12 阅读 130
  1. 导入对应的依赖
<!-- jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.1.1</version>
</dependency>
<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>
<!-- slf4j-simple -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.36</version>
    <!-- <scope>test</scope> -->
    <scope>compile</scope>
</dependency>
  1. 编码测试
  • 连接数据库(先启动redis-service)
  • 操作命令
  • 断开连接!
package com.tuwer;

import redis.clients.jedis.Jedis;

public class TestPing {
    public static void main(String[] args) {
        // 连接
        Jedis jedis = new Jedis("localhost", 6379);
        // 操作
        System.out.println(jedis.ping());
        // 断开连接
        jedis.close();
        // 关闭服务
        //jedis.shutdown();
    }
}

在这里插入图片描述

在这里插入图片描述

  • String
  • List
  • Set
  • Hash
  • Zset
package com.tuwer;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @author 土味儿
 * Date 2022/3/10
 * @version 1.0
 */
public class TextTx {
    public static void main(String[] args) {
        // 连接
        Jedis jedis = new Jedis("localhost", 6379);

        // 清空数据
        jedis.flushDB();
        // 产生数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "tuwer");
        String res = jsonObject.toJSONString();

        // 开启事务
        Transaction multi = jedis.multi();

        try {
            // 操作入列
            multi.set("u1", res);
            multi.set("u2", res);

            // 异常
            //int a = 1/0;

            // 执行事务
            multi.exec();
        }catch (Exception e){
            // 取消事务
            multi.discard();
            e.printStackTrace();
        }finally {
            // 输出
            System.out.println(jedis.get("u1"));
            System.out.println(jedis.get("u2"));
            // 断开连接
            jedis.close();
        }
    }
}

在这里插入图片描述

在这里插入图片描述

举报

相关推荐

0 条评论