栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java整合jedis操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java整合jedis操作

Jedis redis的读写分离:https://blog.csdn.net/qq_51076413/article/details/123462448 docker拉取Redis:https://blog.csdn.net/qq_51076413/article/details/123462701 Java整合Redis:https://blog.csdn.net/qq_51076413/article/details/123462896 使用jedis操作

pom.xml


    org.springframework.boot
    spring-boot-starter-parent
    2.2.4.RELEASE
     




    redis.clients
    jedis



    org.springframework.boot
    spring-boot-starter-data-redis
    
    
        
            io.lettuce
            lettuce-core
        
    



    org.springframework.boot
    spring-boot-starter-test
    test

配置文件配置

哨兵模式 不支持

redis.jedis.xx redis.jedis.xx 不支持哨兵模式

application.properties

############################【Redis】#########################
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=root
# 连接超时时间(毫秒)
spring.redis.timeout=5000ms
# 最大连接数,默认8  redis.jedis.xx 不支持哨兵
spring.redis.jedis.pool.max-active=1024
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=5000ms
# 连接池中的最小空闲连接	redis.jedis.xx 不支持哨兵
spring.redis.jedis.pool.min-idle=5
# 最大空闲连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-idle=200
########### Redis集群的配置 ###########
#spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381
#spring.redis.cluster.max-redirects=5
########### jedis不支持使用哨兵模式(必须redis.lettuce.xx) ###########
# 哨兵模式  主节点的名称
#spring.redis.sentinel.master=mymaster
# 配置节点 IP:节点端口,IP:节点端口,IP:节点端口 
#spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
封装redis配置

RedisConfig .java

package cn.molu.app.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private String timeout;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWait;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Bean
    public JedisPool getJedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大连接数
        jedisPoolConfig.setMaxTotal(maxActive);
        // 最大连接阻塞等待时间
        jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWait.substring(0, maxWait.length() - 2)));
        // 最大空闲连接数
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 最小空闲连接数
        jedisPoolConfig.setMinIdle(minIdle);
        int to = Integer.valueOf(timeout.substring(0, timeout.length() - 2));
        JedisPool jPool = new JedisPool(jedisPoolConfig, host, port, to, password);
        return jPool;
    }
}
jedis操作字符串

添加单条数据 set(key,value); 获取单条数据 get(String key);

jedis.set("ml", "24"); jedis.get("ml");

添加多条数据 mset(String key1,String val1, String key2…);获取 mget(String key, String key2…)

jedis.mset("addr", "sh", "gender", "男", "age", "25"); jedis.mget("addr", "gender", "age");

删除数据 del(String key);

jedis.del(name);

ppApplicationTests.java

import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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


@SpringBootTest
@RunWith(SpringRunner.class)
public class AppApplicationTests {

    @Autowired
    private JedisPool jedisPool;
    private Jedis jedis = null;

    
    @Before
    public void initConnect() {
        jedis = jedisPool.getResource();
        System.out.println("初始化成功!");
    }

    
    @Test
    public void testStringType() {
        // 添加单条数据
        jedis.set("ml", "24");
        // 获取单条数据
        String name = jedis.get("ml");
        System.out.println("name=" + name);
        // 添加多条数据 key:val key:val
        jedis.mset("addr", "sh", "gender", "男", "age", "25");
        // 获取多条数据
        List mVal = jedis.mget("addr", "gender", "age");
        mVal.forEach(System.out::print);
        // 删除数据
        Long delval = jedis.del(name);
        System.out.println("delVal=" + delval);
    }

    
    @After
    public void closeConn() {
        if (jedis != null) {
            jedis.close();
            System.out.println("关闭成功!");
        }
    }
}
jedis操Hash类型

添加单条数据 hset(“redisKey”, “hashKey”, “hashVal”); 获取 hget(“redisKey”, “hashKey”);

jedis.hset("redisKey", "hashKey", "hashVal");

hget("redisKey", "hashKey");

添加多条数据 hmset(“mKey”, map集合); 获取多条数据 hmget(“mKey”, “mapKey”, “mapKey”);

hmset("mKey", map) redisKey map集合

hmget("mKey", "age", "gender"); redisKey map集合的key1 map集合的Key2 …

获取所有数据 jedis.hgetAll(“mKey”);

jedis.hgetAll("mKey"); redisKey

删除数据 hdel(“redisKey”, “hashKey”, “age”);

hdel("redisKey", "hashKey", "age"); redisKey , hashKey, 要删除的数据名, 可以是多个 eg:age , name…

@Test
public void testHash(){
    // 添加数据
    jedis.hset("redisKey", "hashKey", "hashVal");
    // 获取数据
    String val = jedis.hget("redisKey", "hashKey");
    System.out.println("val = " + val);
    // 添加多条数据
    Map map = new HashMap<>();
    map.put("age", "25");
    map.put("gender", "男");
    jedis.hmset("mKey", map);
    List list = jedis.hmget("mKey", "age", "gender");
    list.forEach(System.out::print);
    Map mapVal = jedis.hgetAll("mKey");
    mapVal.entrySet().forEach(item -> System.out.println(item.getKey() + "-" + item.getValue() + " "));
    // 删除 第一个redisKey   第二个 hashKey  第三个是要删除的数据名,可以是多个 eg:age,name..
    jedis.hdel("redisKey", "hashKey", "age");
}
jedis操作list集合

添加数据集合 redisKeys ,val val val

jedis.lpush("redisKeyL", "zs", "ls", "ww"); 左添加

jedis.rpush("redisKeyR", "zl", "tq", "zb"); 右添加

获取数据集合 jedis.lrange(“redisKeyL”, 0, -1);

jedis.lrange("redisKeyL", 0, -1); 左集合 redisKey 开始索引 结束索引(-1为所有)

获取总条数 jedis.llen(“redisKeyL”);

jedis.llen("redisKeyL"); 左侧集合数据总条数

删除数据 lrem(redisKey 删除条数 删除的值)

jedis.lrem("redisKeyL", 1, "ls"); 删除左集合中指定的数据个数和数据值

弹出数据 lpop(“redisKeyR”);

jedis.lpop("redisKeyR"); 左弹出,只会弹出左边的第一条数据(删除)

@Test
public void testList(){
    // 添加数据集合 redisKeys ,val val val
    jedis.lpush("redisKeyL", "zs", "ls", "ww");
    jedis.rpush("redisKeyR", "zl", "tq", "zb");
    // 获取数据集合
    List redisListL = jedis.lrange("redisKeyL", 0, -1);
    redisListL.forEach(System.out::println);
    // 获取总条数
    Long len = jedis.llen("redisKeyL");
    System.out.println("len = " + len);
    // 删除数据 redisKey  删除条数   删除的值
    jedis.lrem("redisKeyL", 1, "ls");
    // 左弹出,只会弹出左边的第一条数据
    String keyR = jedis.lpop("redisKeyR");
    System.out.println("keyR = " + keyR);
}
jedis操作set集合

添加数据 jedis.sadd(“redisKey”, “aaa”, “bbb”, “ccc”, “ddd”);

jedis.sadd("redisKey", "aaa", "bbb", "ccc", "ddd"); redisKey val val val

获取数据 jedis.smembers(“redisKey”);

jedis.smembers("redisKey"); rediskey

获取数据条数 jedis.scard(“redisKey”);

jedis.scard("redisKey"); redisKey

删除数据 srem(redisKey,val) 要删除的数据值, val val val

jedis.srem("redisKey", "aaa", "ccc"); redisKey val val val

@Test
public void testSet(){
    // 添加数据
    jedis.sadd("redisKey", "aaa", "bbb", "ccc", "ddd");
    // 获取数据
    Set setList = jedis.smembers("redisKey");
    setList.forEach(System.out::println);
    // 获取数据条数
    Long len = jedis.scard("redisKey");
    System.out.println("len = " + len);
    // 删除数据 redisKey  要删除的数据值, val val val
    Long srem = jedis.srem("redisKey", "aaa", "ccc");
    System.out.println("srem = " + srem);
}
redis的层级目录
@Test
public void testDir(){
    jedis.set("user:zs:hobby", "pingpong");
    String str = jedis.get("user:zs:hobby");
    System.out.println("str = " + str);
}
key的失效时间

置失效时间

jedis.expire("redisKeyS", 50); 单位 s

jedis.pexpire("redisKeyMS", 50000); 单位 ms

查看失效时间 单位 秒,-1为不失效,-2为已失效

jedis.ttl("redisKeyS"); 获取失效时间 -1为不失效,-2为已失效

存储数据时 设置有效时间

setex("redisKey", 50, "val") 单位 s

jedis.psetex("redisKey", 50000, "val"); 单位 ms

获取有效时间

jedis.pttl("redisKey"); 单位 ms

@Test
public void testExpire(){
    // 添加测试数据
    jedis.set("redisKeyS", "timeout");
    jedis.set("redisKeyMS", "timeout");
    // 设置失效时间 单位秒
    jedis.expire("redisKeyS", 50);
    // 设置失效时间  单位 毫秒
    jedis.pexpire("redisKeyMS", 50000);
    // 查看失效时间 单位 秒,-1为不失效,-2为已失效
    Long s = jedis.ttl("redisKeyS");
    System.out.println("m = " + s);

    // 存储数据时 设置有效时间,单位 秒
    jedis.setex("redisKey", 50, "val");
    // 存储数据时 设置有效时间,单位 毫秒
    jedis.psetex("redisKey", 50000, "val");
    // 获取有效时间  单位  毫秒
    Long ms = jedis.pttl("redisKey");
    System.out.println("ms = " + ms);
}
操作SetParams

redis中不存在该key数据的时候才能设置成功

setParams.nx(); redis中不存在当前 key 的时候才能保存成功,否则不保存(也不报错)

redis存在该key数据的时候才能设置成功

setParams.xx(); redis中存在当前 key 的时候才能保存成功,否则不保存(也不报错)

@Test
public void testSetParams(){
    SetParams setParams = new SetParams();
    // redis中不存在该数据的时候才能设置成功
    //setParams.nx();  
    // 设置失效时间 单位 秒
    //setParams.ex(50);
    // redis存在该数据的时候才能设置成功
    setParams.xx();
    // 设置失效时间 单位 毫秒
    setParams.px(50000);
    jedis.set("redisKey", "val", setParams);
}
获取所有的key

获取当前库中的所有 key * -> 所有 * 表示获取当前库所有key

jedis.keys("*"); * 获取所有

Redis数据库索引(默认为0)spring.redis.database = 1 配置文件中配置的库为当前库(不配默认0库)

@Test
public void testAllKey(){
    // 获取当前数据库中key的数量
    Long size = jedis.dbSize();
    System.out.println("size = " + size);
    // 查询当前库中的所有 key  * -> 所有
    Set keys = jedis.keys("*");
    keys.forEach(System.out::println);
}
Jedis的配置及示例 Jedis相关配置

配置文件

哨兵模式 不支持

redis.jedis.xx redis.jedis.xx 不支持哨兵模式

application.properties

############################【Redis】#########################
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=root
# 连接超时时间(毫秒)
spring.redis.timeout=5000ms
# 最大连接数,默认8  redis.jedis.xx 不支持哨兵
spring.redis.jedis.pool.max-active=1024
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=5000ms
# 连接池中的最小空闲连接	redis.jedis.xx 不支持哨兵
spring.redis.jedis.pool.min-idle=5
# 最大空闲连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-idle=200
########### Redis集群的配置 ###########
#spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381
#spring.redis.cluster.max-redirects=5
########### jedis不支持使用哨兵模式(必须redis.lettuce.xx) ###########
# 哨兵模式  主节点的名称
#spring.redis.sentinel.master=mymaster
# 配置节点 IP:节点端口,IP:节点端口,IP:节点端口 
#spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381

配置类
JedisConfig .java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
public class JedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private String timeout;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private String maxWait;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Bean
    public JedisPool getJedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大连接数
        jedisPoolConfig.setMaxTotal(maxActive);
        // 最大连接阻塞等待时间
        jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWait.substring(0, maxWait.length() - 2)));
        // 最大空闲连接数
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 最小空闲连接数
        jedisPoolConfig.setMinIdle(minIdle);
        Integer timeOut = Integer.valueOf(timeout.substring(0, timeout.length() - 2));
        JedisPool jPool = new JedisPool(jedisPoolConfig, host, port, timeOut, password);
        return jPool;
    }
}
Jedis测试示例代码

测试类
AppApplicationTests .java

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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


@SpringBootTest
@RunWith(SpringRunner.class)
public class AppApplicationTests {

    @Autowired
    private JedisPool jedisPool;

    private Jedis jedis = null;

    
    @Before
    public void initConnect() {
        jedis = jedisPool.getResource();
        System.out.println("初始化成功!");
    }

    
    @Test
    public void testStringType() {
        // 添加单条数据
        jedis.set("ml", "24");
        // 获取单条数据
        String name = jedis.get("ml");
        System.out.println("name=" + name);
        // 添加多条数据 key:val key:val
        jedis.mset("addr", "sh", "gender", "男", "age", "25");
        // 获取多条数据
        List mVal = jedis.mget("addr", "gender", "age");
        mVal.forEach(System.out::print);
        // 删除数据
        Long delval = jedis.del(name);
        System.out.println("delVal=" + delval);
    }

    
    @Test
    public void testHash(){
        // 添加数据
        jedis.hset("redisKey", "hashKey", "hashVal");
        // 获取数据
        String val = jedis.hget("redisKey", "hashKey");
        System.out.println("val = " + val);
        // 添加多条数据
        Map map = new HashMap<>();
        map.put("age", "25");
        map.put("gender", "男");
        jedis.hmset("mKey", map);
        List list = jedis.hmget("mKey", "age", "gender");
        list.forEach(System.out::print);
        Map mapVal = jedis.hgetAll("mKey");
        mapVal.entrySet().forEach(item -> 
               System.out.println("item = " + item.getKey() + "-" + item.getValue() + "    ")
        );
        // 删除 第一个redisKey   第二个 hashKey  第三个是要删除的数据名,可以是多个 eg:age,name..
        jedis.hdel("redisKey", "hashKey", "age");
    }

    
    @Test
    public void testList(){
        // 添加数据集合 redisKeys ,val val val
        jedis.lpush("redisKeyL", "zs", "ls", "ww");
        jedis.rpush("redisKeyR", "zl", "tq", "zb");
        // 获取数据集合
        List redisListL = jedis.lrange("redisKeyL", 0, -1);
        redisListL.forEach(System.out::println);
        // 获取总条数
        Long len = jedis.llen("redisKeyL");
        System.out.println("len = " + len);
        // 删除数据 redisKey  删除条数   删除的值
        jedis.lrem("redisKeyL", 1, "ls");
        // 左弹出,只会弹出左边的第一条数据
        String keyR = jedis.lpop("redisKeyR");
        System.out.println("keyR = " + keyR);
    }

    
    @Test
    public void testSet(){
        // 添加数据
        jedis.sadd("redisKey", "aaa", "bbb", "ccc", "ddd");
        // 获取数据
        Set setList = jedis.smembers("redisKey");
        setList.forEach(System.out::println);
        // 获取数据条数
        Long len = jedis.scard("redisKey");
        System.out.println("len = " + len);
        // 删除数据 redisKey  要删除的数据值, val val val
        Long srem = jedis.srem("redisKey", "aaa", "ccc");
        System.out.println("srem = " + srem);
    }

    
    @Test
    public void testDir(){
        jedis.set("user:zs:hobby", "pingpong");
        String str = jedis.get("user:zs:hobby");
        System.out.println("str = " + str);
    }

    
    @Test
    public void testExpire(){
        // 添加测试数据
        jedis.set("redisKeyS", "timeout");
        jedis.set("redisKeyMS", "timeout");
        // 设置失效时间 单位秒
        jedis.expire("redisKeyS", 50);
        // 设置失效时间  单位 毫秒
        jedis.pexpire("redisKeyMS", 50000);
        // 查看失效时间 单位 秒,-1为不失效,-2为已失效
        Long s = jedis.ttl("redisKeyS");
        System.out.println("m = " + s);

        jedis.setex("redisKey", 50, "val");
        jedis.psetex("redisKey", 50000, "val");
        Long ms = jedis.pttl("redisKey");
        System.out.println("ms = " + ms);
    }

    
    @Test
    public void testSetParams(){
        SetParams setParams = new SetParams();
        // redis中不存在该数据的时候才能设置成功
        //setParams.nx();
        // 设置失效时间 单位 秒
        //setParams.ex(50);
        // redis存在该数据的时候才能设置成功
        setParams.xx();
        // 设置失效时间 单位 毫秒
        setParams.px(50000);
        jedis.set("redisKey", "val", setParams);
    }

    
    @Test
    public void testAllKey(){
        // 获取当前数据库中key的数量
        Long size = jedis.dbSize();
        System.out.println("size = " + size);
        // 查询当前库中的所有 key  * -> 所有
        Set keys = jedis.keys("*");
        keys.forEach(System.out::println);
    }

    
    @After
    public void closeConn() {
        if (jedis != null) {
            jedis.close();
            System.out.println("关闭成功!");
        }
    }
}
redis的读写分离:https://blog.csdn.net/qq_51076413/article/details/123462448 docker拉取Redis:https://blog.csdn.net/qq_51076413/article/details/123462701 Java整合Redis:https://blog.csdn.net/qq_51076413/article/details/123462896
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763990.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号