Jedis

我们要使用Java来操作Redis
什么是Jedis 是Redis官方推荐的java连接开发工具!使用Java操作Redis中间件!

1. 导入对应的依赖

<dependencies>

        <!--导入jedis的包-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

    </dependencies>

2. 编码测试

  • 连接数据库
  • 操作命令
  • 断开连接
public class TestPing {

    public static void main(String[] args){
        // 1. new Jedis 对象即可
        Jedis jedis = new Jedis("127.0.0.1",6379);
        System.out.println(jedis.ping());
    }
}

3.常用API

String

List

Set

Hash

Zset

4.事务

public class TestPing {

    public static void main(String[] args){
        // 1. new Jedis 对象即可
        Jedis jedis = new Jedis("127.0.0.1",6379);

        jedis.flushDB();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","violet");

        // 2.开启事务
        Transaction multi = jedis.multi();
        try {
            String result = jsonObject.toJSONString();
            multi.set("user1",result);
            multi.set("user2",result);
            int i = 1/0; // 代码抛出异常,执行失败
            multi.exec();
        } catch (Exception e) {
            multi.discard();
            e.printStackTrace();
        } finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close();
        }
    }
}