微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

十一Spring Boot整合redis

Spring Boot整合redis

在Spring Boot项目中使用Junit测试Redistemplate的使用

分析:

1.添加启动器依赖: spring-boot-starter-data-redis

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置application.yml中修改redis的连接参数; ( redis服务端需要启动)

spring:
  redis:
    host: localhost
    port: 6379

3.编写测试应用Redistemplate操作redis的五种数据类型(Sting/hash/List/set/sorted set)

package com.test.redis;
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.data.redis.core.Redistemplate;
import org.springframework.test.context.junit4.springrunner;
import java.util.List;
import java.util.Set;
@RunWith(springrunner.class)
@SpringBoottest
public class RedisTest {
    @Autowired
    private Redistemplate redistemplate;
    @Test
    public void test(){
        //1)String字符串
// redistemplate.opsForValue().set("str","String字符串");
        redistemplate.boundValueOps("str").set("String字符串");
        System.out.println("str:"+redistemplate.opsForValue().get("str"));

        //2)hash 散列
        redistemplate.boundHashOps("hashtest").put("name","hash1");
        redistemplate.boundHashOps("hashtest").put("age","16");
        //获取所有域
        Set set = redistemplate.boundHashOps("hashtest").keys();
        System.out.println("hash散列的所有域:"+set);
        //获取所有值
        List list = redistemplate.boundHashOps("hashtest").values();
        System.out.println("hash散列的所有域的值:"+list);

        //3)set集合
        redistemplate.boundSetops("s_key").add("a","b","c");
        set = redistemplate.boundSetops("s_key").members();
        System.out.println("set集合中的所有元素:"+set);
        //4)list列表
        redistemplate.boundListOps("l_key").leftPush("a");
        redistemplate.boundListOps("l_key").leftPush("b");
        redistemplate.boundListOps("l_key").leftPush("c");
        //获取全部元素
        list = redistemplate.boundListOps("l_key").range(0,-1);
        System.out.println("list列表中的所有元素:"+list);

        //5)sorted set
        redistemplate.boundZSetops("sort_key").add("a",100);
        redistemplate.boundZSetops("sort_key").add("b",90);
        redistemplate.boundZSetops("sort_key").add("d",80);
        redistemplate.boundZSetops("sort_key").add("c",80);
        set = redistemplate.boundZSetops("sort_key").range(0,-1);
        System.out.println("sorted set有序集合中的所有元素:"+set);

    }
}

运行结果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐