[7] Jedis-使用Java代码操作Redis

这篇博客介绍了如何在Java中使用Jedis库连接Redis,包括配置Redis.conf,实现ping测试,操作键值对、列表、集合、哈希和有序集合等基本数据类型,以及事务处理。同时,还展示了如何设置主从复制,并提供了JedisPool工具类以实现资源池管理,确保高效和安全的连接操作。
摘要由CSDN通过智能技术生成

一、Jedis

1、maven导入依赖

<dependencies>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.5.1</version>
    </dependency>
</dependencies>

2、配置redis.conf

  1. 去掉bind 127.0.0.1

  2. protected-mode yes改为no

通过redis的注释可以看到,redis开启protected-mode yes后,只允许本机127.0.0.1去连接redis。

当然看到配置文件的注释可以看到,改为no后,就是没有密码也可以直接连接,所以建议加上redis密码。

3、编写Java代码

测试是否可以连接

package com.kj.test;

import redis.clients.jedis.Jedis;

public class TestPing {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("服务器ip",6379);
        jedis.auth("自己的密码");
        System.out.println(jedis.ping());
    }
}

测试api

package com.kj.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.List;
import java.util.Set;

public class TestAPI {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("服务器ip",6379);
        jedis.auth("自己的密码");
        System.out.println(jedis.ping());
        //key
        jedis.set("k1", "v1");
        Set<String> keys = jedis.keys("*");
        System.out.println("key:");
        for (String s : keys) {
            System.out.println(s);
        }
        System.out.println("----------------------");
        //list
        jedis.lpush("list1", "v1", "v2", "v3");
        List<String> list = jedis.lrange("list1", 0, -1);
        System.out.println("list1:");
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println("----------------------");
        //set
        jedis.sadd("set1", "sv1", "sv1", "sv2", "sv3");
        Set<String> set = jedis.smembers("set1");
        System.out.println("set1:");
        for (String s : set) {
            System.out.println(s);
        }
        System.out.println("----------------------");
        //hash
        jedis.hset("hash1", "name", "kj");
        String name = jedis.hget("hash1", "name");
        System.out.println("hash:");
        System.out.println(name);
        System.out.println("----------------------");
        //zset
        jedis.zadd("zset1", 100, "kjj");
        jedis.zadd("zset1", 80, "jk");
        Set<Tuple> zset = jedis.zrangeWithScores("zset1", 0, -1);
        System.out.println("zset1");
        for (Tuple tuple : zset) {
            System.out.println(tuple.getScore() + ":" + tuple.getElement());
        }
        jedis.flushAll();
    }
}

事务

package com.kj.test;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;
import java.util.Set;

public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("47.96.234.106", 6379);
        jedis.auth("kjkjSunflower");
        System.out.println(jedis.ping());
        Transaction transaction = jedis.multi();
        transaction.set("k2", "v2");
        transaction.set("k3", "v3");
        transaction.set("k4", "v4");
        transaction.set("k5", "v5");
        transaction.exec();
        //transaction.discard();
        Set<String> values = jedis.keys("*");
        for (String s : values) {
            System.out.println(s);
        }
    }

    @Test
    public void witch() {
        Jedis jedis = new Jedis("47.96.234.106", 6379);
        jedis.auth("kjkjSunflower");
        System.out.println(jedis.ping());
        jedis.watch("bile");
        Integer bile = Integer.parseInt(jedis.get("bile"));

        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (bile != Integer.parseInt(jedis.get("bile"))) {
            System.out.println("modify");
            jedis.unwatch();
        }else{
            Transaction transaction = jedis.multi();
            transaction.set("bile", "80");
            transaction.exec();
        }
        //transaction.discard();
        String values = jedis.get("bile");
        System.out.println(values);
    }
}

主从复制

package com.kj.test;

import redis.clients.jedis.Jedis;

public class TestMS {
    public static void main(String[] args) {
        Jedis master = new Jedis("47.96.234.106", 6379);
        master.auth("kjkjSunflower");

        Jedis slave = new Jedis("47.96.234.106", 6380);
        slave.auth("kjkjSunflower");

        slave.slaveof("47.96.234.106", 6379);
        master.set("age", "22");
        // 可能获取不到值,因为内存速度开快,需要多来几次
        System.out.println(slave.get("age"));
    }
}

Jedis Pool

工具类

package com.kj.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {

    private static volatile JedisPool pool = null;

    private JedisPoolUtil() {
    }

    public static JedisPool getPoolInstance() {
        if (null == pool) {
            synchronized (JedisPoolUtil.class) {
                if (null == pool) {
                    JedisPoolConfig config = new JedisPoolConfig();
                    //最多有多少空闲的jedis
                    config.setMaxTotal(1000);
                    config.setMaxIdle(32);
                    config.setMaxWaitMillis(200000);
                    config.setMinIdle(10);

                    //获取jedis实例时,是否检查连接可用性(ping())
                    //需要redis和你的程序在同一主机上
                    config.setTestOnBorrow(false);
                    pool = new JedisPool(config, "你的IP", 6379);
                }
            }
        }
        return pool;
    }

    public static void release(Jedis jedis) {
        if(null != jedis){
            jedis.close();
        }
    }
}

测试

package com.kj.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class TestPool {
    public static void main(String[] args) {
        JedisPool pool = JedisPoolUtil.getPoolInstance();
        JedisPool pool2 = JedisPoolUtil.getPoolInstance();
        System.out.println(pool == pool2);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.auth("kjkjSunflower");
            jedis.set("aa","bb");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JedisPoolUtil.release(jedis);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值