springboot中 Redis基本操作

  • 在使用springboot时,我们有时候会整合Redis进行相关操作,首先在pom.xml中添加redis相关依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  • 在application.properties中添加相关配置,更具体的配置可以自行寻找
#=========redis基础配置=========
spring.redis.database=0
spring.redis.host=192.168.180.130
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000

#=========redis线程池设置=========
# 连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=200

#连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=200

# 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=2000

# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
spring.redis.pool.max-wait=1000

操作类

配置好后,使用的操作类主要有两种

  • RedisTemplate
  • StringRedisTemplate

【RedisTemplate】
RedisTemplate是最基本的操作类,它默认的序列化方式是JdkSerializationRedisSerializer,在存值时,键值会被序列化为字节数组,可读性差,取值时也是一样,如果redis中存的值正常的字符串形式,取值时将返回null
【StringRedisTemplate】
StringRedisTemplate继承于 RedisTemplate<String, String>,默认的序列化方式是

  • StringRedisSerializer,存值取值都是按照字符串的形式
  • 如果存的是字符串,建议直接使用StringRedisTemplate

如果是对象,可采取以下两种方法

  1. 使用RedisTemplate存,取值时可以直接强转
  2. 使用StringRedisTemplate,存值得时候使用json工具类将对象转化为json字符串,取值时再将json字符串转为对象
    ##创建属性
	@Autowired
    StudentMapper studentMapper;
    //设置  RedisTemplate<String,String>  确定序列化
    @Autowired
    RedisTemplate<String,String> redisTemplate1;
    @Autowired
    RedisTemplate redisTemplate;
    //可以使用自增自减,查询所有键keys
    @Autowired
    StringRedisTemplate stringRedisTemplate;

String类型代码

public List<Student> select() {
        List<Student> list = studentMapper.select();
        for (Student s : list) {
            redisTemplate.opsForValue().set("Student:" + s.getId(), s.getName());
            redisTemplate.expire("Student:" + s.getId(), 30, TimeUnit.SECONDS);
            System.out.println("判断是否存在:" + redisTemplate.hasKey("Student:" + s.getId()));
            System.out.println("数据类型为:" + redisTemplate.type("Student:" + s.getId()));
            System.out.println("Student:" + s.getId() + "剩余时间: " + redisTemplate.getExpire("Student:" + s.getId()));
            System.out.println("Student:" + s.getId() + ": " + redisTemplate.opsForValue().get("Student:" + s.getId()));
        }
        //自增自减需自定义序列化规则
        /*stringRedisTemplate.opsForValue().set("num","15");
        System.out.println(redisTemplate.opsForValue().get("num"));
        stringRedisTemplate.opsForValue().increment("num");
        System.out.println(redisTemplate.opsForValue().get("num"));
        stringRedisTemplate.opsForValue().decrement("num");
        System.out.println(redisTemplate.opsForValue().get("num"));*/

        //若key不存在,设值
        //redisTemplate.opsForValue().setIfAbsent("name", "test2");

        /*//批量k,v设值
        Map<String, String> map = new HashMap<String, String>();
        map.put("k1", "v1");
        map.put("k2", "v2");
        map.put("k3", "v3");
        redisTemplate.opsForValue().multiSet(map);

        //批量取值
        List<String> keys = new ArrayList<String>();
        keys.add("k1");
        keys.add("k2");
        keys.add("k3");
        List<String> values = redisTemplate.opsForValue().multiGet(keys);
        System.out.println(values);
        */

        //遍历系统所有键
        System.out.println("遍历所有键如下----------");
        Set<String> keys = stringRedisTemplate.keys("*");
        /*System.out.println(keys);
        System.out.println("------------------");*/
        for(String s:keys){
            System.out.println(redisTemplate.opsForValue().get(s));
        }
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println(key + " : " + redisTemplate.opsForValue().get(key));
        }
        return list;
    }

自增自减等操作需要确定序列化

public void no1(){
        /*
		使用StringRedisTemplate
		stringRedisTemplate.opsForValue().set("num","5");
        System.out.println(stringRedisTemplate.opsForValue().get("num"));
        stringRedisTemplate.opsForValue().increment("num",5);
        System.out.println(stringRedisTemplate.opsForValue().get("num"));
        stringRedisTemplate.opsForValue().decrement("num",10);
        System.out.println(stringRedisTemplate.opsForValue().get("num"));*/

        redisTemplate1.opsForValue().set("num","5");
        System.out.println(redisTemplate1.opsForValue().get("num"));
        redisTemplate1.opsForValue().increment("num",5);
        System.out.println(redisTemplate1.opsForValue().get("num"));
        redisTemplate1.opsForValue().decrement("num",10);
        System.out.println(redisTemplate1.opsForValue().get("num"));
    }

List操作

public List<Student> list() {
        /*
        * 获取指定下标元素
        * redisTemplate.opsForList().index(name,i);
        *
        * 重新设置指定下标元素
        * redisTemplate.opsForList().set("product:list", 1, "dell xps13");
        * */

        List<Student> list = studentMapper.select();
        //将整个list存放
        redisTemplate.opsForList().leftPushAll("lists",list);
        System.out.println(redisTemplate.opsForList().range("lists",0,6));
        //一般存放
        for (Student s : list) {
            redisTemplate.opsForList().leftPush("Student:", s.getId() + "");
        }
        redisTemplate.opsForList().leftPush("man", list);
        List list2 = (List) redisTemplate.opsForList().leftPop("man");
        //直接将list放入redis
        System.out.println(list2);
        System.out.println(redisTemplate.opsForList().range("man", 0, 6));
        redisTemplate.expire("Student:", 30, TimeUnit.SECONDS);
        //左边删除一个并返回
        System.out.println(redisTemplate.opsForList().leftPop("Student:"));
        System.out.println(redisTemplate.opsForList().range("Student:", 0, 6));
        //存储类
        for (Student s : list) {
            redisTemplate.opsForList().leftPush("class", s);
        }
        System.out.println(redisTemplate.opsForList().range("class", 0, 6));
        Student s = (Student) redisTemplate.opsForList().leftPop("class");
        System.out.println(s.toString());
        return list;
    }

HashMap操作

public void map(){
        List<Student> list = studentMapper.select();
        //一个一个添加
        HashMap map = new HashMap<>();
        for(Student s:list){
            map.put(s.getId(),s.getName());
            redisTemplate.opsForHash().put("Student:1",s.getId(),s.getName());
        }
        System.out.println(map);
        redisTemplate.opsForHash().putAll("Student:2",map);
        for (Student s:list){
            System.out.println(redisTemplate.opsForHash().get("Student:2",s.getId()));
        }
        //删除
        for (int i = 0 ;i < list.size();i++){
            if(i==0||i==1){
                redisTemplate.opsForHash().delete("Student:1",list.get(i).getId());
            }
        }
        //获取
        for(Student s:list){
            System.out.println(redisTemplate.opsForHash().get("Student:1",s.getId()));
        }
        //获取全部key value
        System.out.println(redisTemplate.opsForHash().entries("Student:2"));
        //获取key
        System.out.println(redisTemplate.opsForHash().keys("Student:2"));
        //获取value
        System.out.println(redisTemplate.opsForHash().values("Student:2"));
    }

Set操作

public void set(){
        List<Student> list = studentMapper.select();
        //添加Set
        for (Student s:list){
            redisTemplate.opsForSet().add("mySet",s.getName());
        }
        //删除元素
        redisTemplate.opsForSet().remove("mySet", list.get(0).getName());
        //查询是否存在
        System.out.println(redisTemplate.opsForSet().isMember("mySet",list.get(2).getName()));
        //获取该Set集合
        Set member = redisTemplate.opsForSet().members("mySet");
        System.out.println(member);
        redisTemplate.opsForSet().add("set:1","a","b","c","d","e","f","g");
        redisTemplate.opsForSet().add("set:2","e","f","g","h","i","j");
        redisTemplate.opsForSet().add("set:3","a","b","c");
        //交集
        Set intersect = redisTemplate.opsForSet().intersect("set:1","set:2");
        System.out.println(intersect);
        //求多个set的交集  redisTemplate.opsForSet().differenceAndStore()
        //并集
        Set union = redisTemplate.opsForSet().union("set:1","set:2");
        System.out.println(union);
        //差集
        //k1为全集
        Set difference = redisTemplate.opsForSet().difference("set:1","set:3");
        System.out.println(difference);
    }

可以参考另一篇文章 https://www.jianshu.com/nb/29133493

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用Redis有多种方式,下面是一个简单的示例: 首先,确保在`pom.xml`文件添加Redis的依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 然后,在`application.properties`(或`application.yml`)文件配置Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 接下来,我们可以使用Spring Data Redis提供的`RedisTemplate`进行Redis操作。例如,存储和获取一个字符串值: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisExample { @Autowired private RedisTemplate<String, String> redisTemplate; public void setValue(String key, String value) { redisTemplate.opsForValue().set(key, value); } public String getValue(String key) { return redisTemplate.opsForValue().get(key); } } ``` 上面的示例,我们使用了`RedisTemplate`来执行Redis操作。通过自动注入,我们可以在Spring Boot应用程序的其他类使用`RedisExample`类。在其他地方,我们可以通过调用`setValue`方法来存储一个键值对,通过调用`getValue`方法来获取对应的值。 这只是RedisSpring Boot的基本用法示例,你可以根据自己的需求进行更复杂的操作,如存储对象、使用Hash等。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值