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

Redis-Java整合Redis---Jedis

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

Redis-Java整合Redis---Jedis

Java整合Redis—Jedis 所需要的jar包

redis.clients
jedis
3.2.0

连接Redis的注意事项
  • 禁用Linux的防火墙:Linux(CentOS7)里执行命令 systemctl stop/disable firewalld.service
  • redis.conf中注释掉bind 127.0.0.1 (如果指定了bind,则说明只允许来自指定网卡的Redis请求。如果没有指定,就说明可以接受来自任意一个网卡的Redis请求。)
  • redis.conf中设置 protected-mode no (此时外部网络可以直接访问)
Jedis的常用操作 连接主机
 // 创建连接
  Jedis jedis = new Jedis("192.168.150.101", 6379);  // 代表redis的端口号和连接地址
操作字符串
  public void demo01() {
        // 创建连接
        Jedis jedis = new Jedis("192.168.150.101", 6379);
        // 在jedis中添加数据
        jedis.set("name", "lucy");

        // 获取数据
        String name = jedis.get("name");
        System.out.println(name);
        // 批量设置字符串
        jedis.mset("key01", "value1", "key02", "value02");
        List mget = jedis.mget("key01", "key02");
        for (String s : mget) {
            System.out.println(mget);
        }
        // 批量获取
        Set keys = jedis.keys("*");
        for (String key : keys) {
            System.out.println(key);
        }
        // 判断是否有这个字符串
        jedis.exists("key01");
        // 返回过期时间
        Long key01 = jedis.ttl("key01");
        // 设置过期时间,以秒为单位
        jedis.expire("key01",200);
    }

操作List
    public void demo02() {


        Jedis jedis = new Jedis("192.168.150.101", 6379);
        // 添加list
        jedis.lpush("k1", "lucy", "jack", "mary");
        List k1 = jedis.lrange("k1", 0, -1);
        for (String s : k1) {
            System.out.println(s);
        }


        // 将多个值存放入集合中
        jedis.lpush("user", "aaa", "bbb", "ccc");

        // 在对应的list集合中插入一个元素(一般叫尾插,因为他会出现在集合的头部,也就是栈的顶端)
        jedis.lpush("user", "aaa");

       
        List user = jedis.lrange("user", 0, -1);
        
        jedis.ltrim("user", 0, 1);

     
        jedis.lpop("user");

       
        jedis.rpush("user", "ddd");

       
        jedis.rpop("user");

       
        jedis.lset("user", 0, "ddd");

        // 返回list集合的长度
        jedis.llen("user");

        //获取到list下标为0的元素值
        jedis.lindex("user", 0);

        // 给list集合进行排序
        jedis.sort("user");


    }
操作set集合
   public void demo03() {
        Jedis jedis = new Jedis("192.168.150.101", 6379);
        //将一个或多个 member 元素加入到集合 key 当中,已经存在于集合的 member 元素将被忽略。
        jedis.sadd("username", "lucy", "jack", "mary", "lucy");
        // 返回所有元素
        Set name = jedis.smembers("username");
        for (String s : name) {
            System.out.println(s);
        }
        // 返回集合 key 的基数(集合中元素的数量)。
        jedis.scard("username");

        //Sdiff 命令返回给定集合之间的差集。不存在的集合 key 将视为空集。
        Set sdiff = jedis.sdiff("username","username2"); //返回值为username-username2的值

        // sinter 返回给定集合的交集
        Set sinter = jedis.sinter("username", "username2");

        //判断lucy是否是username中的一个元素
        jedis.sismember("username","lucy");

        //Spop 命令用于移除并返回集合中的一个随机元素。
        String username = jedis.spop("username");

        // Smove 命令将指定成员 lucy 元素从 username 集合移动到 username2 集合,SMOVE 是原子性操作。
        // 如果 username 集合不存在或不包含指定的 lucy 元素,则 SMOVE 命令不执行任何操作,仅返回 0 。
        // 否则, lucy 元素从 username 集合中被移除,并添加到 username2 集合中去。
        // 当 username2 集合已经包含 lucy 元素时, SMOVE 命令只是简单地将 username 集合中的 lucy 元素删除。
        // 当 username 或 username2 不是集合类型时,返回一个错误
        Long smove = jedis.smove("username", "username2", "lucy");

        // srandmember 命令用于返回集合中的一个随机元素,不会删除集合中的元素
        String username1 = jedis.srandmember("username");

        //srem 命令用于移除集合中的一个或多个成员元素,不存在的成员元素会被忽略。
        jedis.srem("username", "jack","lucy");

        //sunion 命令返回给定集合的并集。不存在的集合 key 被视为空集。
        Set sunion = jedis.sunion("username", "username2");
    }
操作Hash
  @Test
    public void demo04() {
        Jedis jedis = new Jedis("192.168.150.101", 6379);
        // 添加一条记录 如果users存在 则更新value,如果不存在则进行添加
        jedis.hset("users", "age", "20");
        // 获取hash中指定的数据
        String hget = jedis.hget("users", "age");
        System.out.println(hget);

        //删除指定key的指定fields值,可以指定一个或者多个,不存在的field则被忽略
        jedis.hdel("users","age","username");

        //获取指定hash中全部的数据
        Map map = jedis.hgetAll("users");

        // 判断hash中 指定的field是否存在
        Boolean hexists = jedis.hexists("users", "username");

        // 获取哈希表中字段的数量
        Long users = jedis.hlen("users");
    }

操作zset
   public void demo05() {
        Jedis jedis = new Jedis("192.168.150.101", 6379);
        //添加元素以及该元素对应的分数到集合,分数为double类型
        jedis.zadd("china", 100d, "shanghai");

        //按照定义的起始下标与结束下标正序遍历出相应元素,结束下标为-1则表示zset的最后元素
        Set china = jedis.zrange("china", 0, -1);
        System.out.println(china);

        //批量添加元素
        Map map = new HashMap<>();
        map.put("b", 65.0);
        map.put("c", 75.0);
        map.put("d", 90.5);
        jedis.zadd("score", map);

        //按照定义的起始下标与结束下标倒序遍历出相应元素,结束下标为-1则表示zset的最后元素
        jedis.zrevrange("score", 1, 3);

        // 按照定义的分数区间正序获取元素
        Set score = jedis.zrangeByScore("score", 65.0, 75);

        //按照定义的分数区间倒序遍历元素
        Set score1 = jedis.zrevrangeByScore("score", 75.0, 90.5);

        //按照定义的分数区间正序遍历元素,同时带出相应分数
        Set score2 = jedis.zrangeByScoreWithScores("score", 75.0, 90.5);

        //获取定义的分数区间的元素数量
        Long score3 = jedis.zcount("score", 75.0, 90.5);

        // 获取元素的score值
        Double zscore = jedis.zscore("score", "b");

        // 删除指定元素
        Long zrem = jedis.zrem("score", "a");

        // 通过下标范围删除元素
        Long score4 = jedis.zremrangeByRank("score", 1, 2);

        // 通过分数范围删除元素
        jedis.zremrangeByScore("score", 60.0, 85.0);

        // 增加指定元素的分数,返回的指定的分数
        Double zincrby = jedis.zincrby("score", 6.0, "a");
        
    }
SpringBoot整合Redis 引入相关的jar包
    
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
        
            org.apache.commons
            commons-pool2
            2.6.0
        
application.properties配置redis配置
#Redis服务器地址
spring.redis.host=192.168.150.101
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database= 0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
redis的配置类
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

测试
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public String testRedis(){
        //设置普通值到Redis中
        redisTemplate.opsForValue().set("name","lucy");
        //从redis中获取普通值
        String name = (String)redisTemplate.opsForValue().get("name");
        // 获取元素过期时间
        redisTemplate.getExpire("name");

        //删除对应的key
        Boolean name1 = redisTemplate.delete("name");

        // 普通设置值并设置时间
        redisTemplate.opsForValue().set("key01", "1", 100, TimeUnit.SECONDS);

        // 递增,设置增加的值
        redisTemplate.opsForValue().increment("key01", 5);

        // 递减,设置减少的值
        redisTemplate.opsForValue().increment("key01", -5);

        return name;

    }
}
Jedis的连接池工具类
public class JedisPoolUtil {
    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil() {
    }

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(200);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100 * 1000);
                    poolConfig.setBlockWhenExhausted(true);
                    poolConfig.setTestOnBorrow(true);  // ping  PONG

                    jedisPool = new JedisPool(poolConfig, "192.168.150.101", 6379, 60000);
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            jedisPool.returnResource(jedis);
        }
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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