Jedis

Jedis是Redis官方推荐的java连接工具!是使用java操作redis的中间件。

若要通过jedis连接远程服务器的redis,需要对服务器的redis进行如下配置:

一、改服务器提供商的安全组规则,开放6379端口

二、修改服务器的防火墙规则,开放6379端口(CentOS7)

命令如下:

firewall-cmd --zone=public --add-port=6379/tcp --permanent

三、修改redis的配置文件

(1)把protected-mode yes修改为no

(2)注释掉bind

(3)为了安全起见,设置一个密码(否则别人通过公网ip+端口号就能访问到)

​ 如: requirepass 123456

具体操作:https://www.cnblogs.com/coderhu1/p/13922634.html

带密码的客户端连接方法

带密码的客户端连接方法一

redis-cli -a 123456

-a 为连接密码

[root@shiyaochang bin]# redis-server sconfig/redis.conf 
[root@shiyaochang bin]# redis-cli -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:6379>

密码验证方法二:

在命令行输入:auth 123456 #123456是密码

[root@shiyaochang bin]# redis-server sconfig/redis.conf 
[root@shiyaochang bin]# redis-cli
127.0.0.1:6379> auth 123456
OK

测试:创建一个简单地maven项目

1.导入对应的依赖

<dependencies>
    <!--导入jedis依赖-->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.5.1</version>
    </dependency>
    <!--fastjson-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.45</version>
    </dependency>
</dependencies>

2.编码测试

  • 连接数据库
  • 操作命令
  • 断开连接
package sovzn;

import redis.clients.jedis.Jedis;

public class TestPing {
    public static void main(String[] args) {
        //1.创建jedis对象
        //参数:服务器ip   端口号
        Jedis jedis = new Jedis("8.131.56.126",6379);
        // 如果 Redis 服务设置了密码,需要下面这行,没有就不需要
        jedis.auth("123456");
        System.out.println( jedis.ping() );
        // ********************jedis所有的命名和redis的完全一样***********************
        jedis.set("test","test");
        System.out.println(jedis.get("test"));
         jedis.disconnect();//断开连接
    }
}

执行结果:
PONG
test

Process finished with exit code 0

事务

package sovzn;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class TestMulti2 {
    public static void main(String[] args) {
        //创建客户端连接服务端,redis服务端需要被开启
        Jedis jedis = new Jedis("8.131.56.126",6379);
        jedis.auth("123456");
        jedis.flushDB();
        jedis.set("a","a");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello", "world");
        jsonObject.put("name", "java");
        Transaction multi = jedis.multi();   //开启事务
        String result = jsonObject.toJSONString();

            //向redis存入一条数据
            multi.set("json3", result);
            //给key为a的字符串类型的值+1,这里引发命令异常
            multi.incr("a");  
            
            //再存入一条数据
            multi.set("json4", result);
            //执行事务
            multi.exec();

            System.out.println(jedis.get("json3"));
            System.out.println(jedis.get("a"));
            System.out.println(jedis.get("json4"));
            
            jedis.close();//关闭连接

    }
}

执行结果:
json3:{"name":"java","hello":"world"}
a:a
json4:{"name":"java","hello":"world"}

Process finished with exit code 0

从上述事例中可以再次证明,redis事务中即使有命令执行失败,其余的命令依然被执行,即反原子性

SpringBoot整合Redis

项目地址:链接:https://pan.baidu.com/s/1Xs8PIxAeONcuW85-8a9RCg 提取码:k6k7

说明:在springboot2.X后,原来使用的jedis被替换成为了lettuce

两者区别:

  • jedis: 采用的是直连,多个线程操作的话是不安全的,可以使用jedis pool连接池来避免。更像BIO
  • lettuce:采用netty,实例可以在多个线程中进行共享,不存在不安全的情况,更像NIO模式。

查看启动器spring-boot-starter-data-redis的底层依赖可以发现有io.lettuce:

<dependency>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
      <version>6.0.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>

继续查看依赖io.lettuce的底层依赖可以发现有很多netty依赖,如:

<dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-common</artifactId>
      <version>4.1.56.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-handler</artifactId>
      <version>4.1.56.Final</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-transport</artifactId>
      <version>4.1.56.Final</version>
      <scope>compile</scope>
    </dependency>

RedisAutoConfiguration源码分析:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(name = {"redisTemplate"} 
     //ConditionalOnMissingBean:如果没有这个bean(redisTemplate),就会创建
     //也就是说我们可以自定义一个bean:redisTemplate来替换这个默认的 
     //---------------------传入的对象都得使用序列化---------------------------
    )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        //这个默认的RedisTemplate,没有过多的设置
        //两个泛型都是<Object, Object>类型,后续自定义转换为<String, Object>
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    //由于String类型是redis中最常使用的类型,所有单独提出来了一个操作String类型的bean!
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

整合测试

1.导入依赖:

<!--springboot整合操作redis-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

2.连接配置

#SpringBoot 所有的配置类都会有一个自动配置类 如 RedisAutoConfiguration
#每一个自动配置类都会绑定一个XXXXproperties配置信息类 RedisProperties
#XXXXproperties里所具有的属性,就是咱们能够在application.properties里能够配置的东西

#配置redis
#redis服务器ip
spring.redis.host=8.131.56.126  
#端口号
spring.redis.port=6379
spring.redis.password=123456

3.测试


@SpringBootTest
class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        //方法说明:
        //opsForValue():操作字符串String
        //opsForList():操作List
        //opsForSet():操作Set
        //opsForHash():操作Hash
        //..........等
        //jedis与redis的语法几乎完全相同,lettuce与redis的语法大同小异。
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库

        redisTemplate.opsForValue().set("mykey","shiyaochang");
        //System.out.println(redisTemplate.opsForValue().get("mykey"));
        String s= (String) redisTemplate.opsForValue().get("mykey");
        System.out.println(s);
        System.out.println(redisTemplate.keys("*"));
    }

}

执行结果:成功打印出"shiyaochang"
    
shiyaochang
[]
2021-02-10 17:02:52.143  INFO 5444 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code 0

但是我们在redis客户端查看key值会发现:

127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x05mykey"
127.0.0.1:6379> 

刚才程序存进去的key值”mykey”变成了:”\xac\xed\x00\x05t\x00\x05mykey”
这是因为默认的序列化方式是JDK序列化,产生了这样的key,我们可以使用json来序列化,这得自定义配置类中的RedisTemplate。

往redis中存储对象:

//User对象
package com.sovzn.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private String name;
private Integer age;
}

1.使用json来传递对象

@Autowired
private RedisTemplate redisTemplate;
@Test
    public  void  test() throws JsonProcessingException {
           RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库
        //使用json来传递对象,即使对象没有序列化,也能成功存入
         User user = new User("sovzn", 22);
         String s = new ObjectMapper().writeValueAsString(user);
         redisTemplate.opsForValue().set("user",s);
         System.out.println(redisTemplate.opsForValue().get("user"));
         System.out.println(redisTemplate.keys("*"));

     }

执行结果:

{"name":"sovzn","age":22}
[]

2021-02-11 15:39:07.594  INFO 5240 --- [extShutdownHook]

Process finished with exit code 0

#redis客户端查看key值
127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x04user"
127.0.0.1:6379> 

2.未序列化对象直接存入redis:

@Autowired
private RedisTemplate redisTemplate;
@Test
    public  void  test() throws JsonProcessingException {
           RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库
         User user = new User("sovzn", 22);
         redisTemplate.opsForValue().set("user",user);
         System.out.println(redisTemplate.opsForValue().get("user"));
         System.out.println(redisTemplate.keys("*"));

     }
     
 执行结果:
 org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.sovzn.pojo.User]
 
 //报错提示对象没有序列化
     

3.序列化对象后存入redis

//序列化User,使其实现Serializable
public class User implements Serializable {
private String name;
private Integer age;
}
@Autowired
private RedisTemplate redisTemplate;
 @Test
    public  void  test() throws JsonProcessingException {
           RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库
         User user = new User("sovzn", 22);
         redisTemplate.opsForValue().set("user",user);
         //System.out.println(redisTemplate.opsForValue().get("user"));
         User user1= (User) redisTemplate.opsForValue().get("user");
         System.out.println(user1);
         System.out.println(redisTemplate.keys("*"));
     }
     
 执行结果: //成功将对象存入redis,key值没有序列化,所有打印不出
     
User(name=sovzn, age=22)
[]   
Process finished with exit code 0
#redis客户端查看key值
127.0.0.1:6379> keys *
1) "\xac\xed\x00\x05t\x00\x04user"
127.0.0.1:6379> 

自定义RedisTemplate

package com.sovzn.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    //编写自定义的RedisTemplate
   @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //为了开发方便一般使用<String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        //-------------------序列化配置----------------------
        //json序列化,将任意对象解析为序列化后的json数据
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        //通过ObjectMapper转义json序列化
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //String的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}

测试:

因为我们在自定义的RedisTemplate中对传入的对象完成了序列化,因此pojo类无需再通过实现Serializable类来序列化。

@Component
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User  {
private String name;
private Integer age;
}
@Autowired
@Qualifier("redisTemplate")
    private RedisTemplate redisTemplate; 
@Test
    public  void  test1() throws JsonProcessingException {

        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库
        User user = new User("师耀昌", 2);
        redisTemplate.opsForValue().set("user",user);
        User u= (User) redisTemplate.opsForValue().get("user");
        System.out.println(u);
        System.out.println(redisTemplate.keys("*"));
    }

执行结果:
User(name=师耀昌, age=2)
[user]

2021-02-11 16:33:32.735  INFO 4144 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
Process finished with exit code 0
#redis客户端查看key值
127.0.0.1:6379> keys *
1) "user"
127.0.0.1:6379> 

在redis客户端通过命令存入的数据,通过RedisTemplate无法获得?

封装RedisTemplate的方法

在正式开发中,为了方便使用,减轻代码的繁琐,一般都会对RedisTemplate操作做redis的原生代码进行封装,如下:

package com.sovzn.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================common============================
    /**
     * 指定缓存失效时间
     * @param key  键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }


    // ============================String=============================

    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 普通缓存放入并设置时间
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 递增
     * @param key   键
     * @param delta 要增加几(大于0)
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }


    /**
     * 递减
     * @param key   键
     * @param delta 要减少几(小于0)
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     * @param key  键 不能为null
     * @param item 项 不能为null
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet 并设置时间
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */

    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */

    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

}

测试调用封装的工具类:

//注入工具类
@Autowired
    private RedisUtil redisUtil;

  @Test
    public  void  test2() throws JsonProcessingException {

        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushAll();//清空数据库
        User user = new User("师耀昌", 2);
        redisUtil.set("name",user);
        System.out.println(redisUtil.get("name"));
        System.out.println(redisTemplate.keys("*"));

    }


执行结果:
User(name=师耀昌, age=2)
[name]

2021-02-11 16:58:33.100  INFO 13524 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code 0