Java使用jedis连接NoSQL数据库Redis写入数据并读取出来

x33g5p2x  于2022-02-07 转载在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(369)

(1)当然需要先启动Redis数据库,关于启动Redis数据库,参考下面这篇文章:

https://zhangphil.blog.csdn.net/article/details/122535147

https://zhangphil.blog.csdn.net/article/details/122535147

(2)用idea创建一个maven项目工程,在pom.xml添加jedis依赖:

<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.0.1</version>
        </dependency>

(3)编写一个简单的Java程序代码实现对Redis数据库的读与写:

import org.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

public class MainClass {
    public static void main(String[] args) {
        //JedisPool配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxWait(Duration.ofMillis(3000));
        jedisPoolConfig.setMaxTotal(1000);
        jedisPoolConfig.setMaxIdle(500);

        //JedisPool实例
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,
                "127.0.0.1", //host主机
                6379//默认端口
        );
        //Jedis连接池依照JedisPool获得Jedis
        Jedis jedis = jedisPool.getResource();

        //输出PONG 则成功连接到Redis
        System.out.println(jedis.ping());

        //写入一个值测试
        String key = "zhangphil";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("city", "Chengdu");
        jsonObject.put("it", "Java,Android,Python");

        jedis.set(key, jsonObject.toString());

        //从Redis读取刚才写入的值
        System.out.println(jedis.get(key));

        //关闭jedis,释放jedis连接池资源
        jedis.close();
    }
}

运行输出日志:

PONG
{"city":"Chengdu","it":"Java,Android,Python"}

相关文章