SpringBoot整合redis

本文介绍了SpringBoot如何与redis进行整合,详细讲解了导入依赖、配置文件设置、使用RedisTemplate进行数据操作,包括List、Hash、String和Set四种数据类型的增删查改,以及各自的应用场景。
摘要由CSDN通过智能技术生成
1. redis的特点

redis一种数据存储在内存的数据库,它具有高速读写数据的功能,主要核心如下:

  • k-v键值对
  • 缓存(不易变动的数据)
  • 持久化
2. SpringBoot整合redis
2.1 导入依赖pom.xml
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>redis.clients</groupId>
                    <artifactId>jedis</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
		<!--redis连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
2.2 redis配置文件application.yml
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
2.3 redis的模板引擎RedisTemplate

由于普通的连接根本没有办法直接将对象直接存入 Redis 内存中,我们需要替代的方案:将对象序列化(可以简单的理解为继承Serializable接口)。我们可以把对象序列化之后存入Redis缓存中,然后在取出的时候又通过转换器,将序列化之后的对象反序列化回对象,这样就完成了我们的要求:
public class StringRedisTemplate extends RedisTemplate<String, String>
RedisTemplate:写数据到redis内存,从内存中取数据。

2.4 根据StringRedisTemplate操作4种数据
2.4.1 List操作
  • 增添数据
    stringRedisTemplate.opsForList().rightPush(k, v):依次从右边添加元素到链表中
    stringRedisTemplate.opsForList().leftPush(k, v):依次从左边添加元素到链表中
  • 查询数据
    stringRedisTemplate.opsForList().range("a", 0, -1):查询类别为a的所有元素,返回list集合
    stringRedisTemplate.opsForList().range("b", 0, 4):查询类型为b的前4个元素,返回list集合
  • 删除数据
    stringRedisTemplate.opsForList().remove("a", 1, "97"):删除一个先进入的值为97的元素
    stringRedisTemplate.opsForList().remove("b", 0, "48"):删除所有值为48的元素

作用范围:(1)消息队列 (2)分页功能

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

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void contextLoads() {
    }

    /**
     * list数据类型适合消息队列的场景:比如12306并发量高,
     * 而同一时间内只能处理指定数量的数据,必须满足先进先出原则
     * 其与数据等待
     */
    @Test
    public void testPushRedisList(){
        //rightPush依次由右边添加
        stringRedisTemplate.opsForList().rightPush("a","97");
        stringRedisTemplate.opsForList().rightPush("a","98");
        stringRedisTemplate.opsForList().rightPush("a","99");
        stringRedisTemplate.opsForList().rightPush("b","100");
        stringRedisTemplate.opsForList().rightPush("b","101");
        stringRedisTemplate.opsForList().leftPush("b","48");
    }

    /**
     * 查询List
     */
    @Test
    public void testFindList(){
        //查询类别对应的所有元素
        List<String> list = stringRedisTemplate.opsForList().range("a", 0, -1);
        System.out.println(list);
        //查询前3个元素
        List<String> list1 = stringRedisTemplate.opsForList().range("b", 0, 4);
        System.out.println(list1);
    }

    @Test
    public void testRemoveList(){
        //删除一个先进入的值为97的元素
        stringRedisTemplate.opsForList().remove("a",1,"97");
        //删除所有值为48的元素
        stringRedisTemplate.opsForList().remove("b",0,"48");
    }
}
2.4.2 Hash操作
  • 增添数据
    stringRedisTemplate.opsForHash().put("myHash", "a", "97"):增加名为myHash的map集合数据
  • 获取数据
    stringRedisTemplate.opsForHash().get("myHash", "a"):获取名为myHash集合对应key为a的value数据。
    stringRedisTemplate.opsForHash().entries("myHash")遍历myHash集合获取数据
    作用范围:(1)单点登录
    	//获取Map对象
        Map<Object, Object> hash = stringRedisTemplate.opsForHash().entries("myHash");
        //遍历Map对象
        for (Map.Entry<Object, Object> entry : hash.entrySet()) {
            System.out.println("key=" + entry.getKey() + "\t" + "value=" + entry.getValue());
        }
    
  • 删除数据
    stringRedisTemplate.opsForHash().delete("myHash","b")
	/**
     * hash的put操作,如果key相同,则后面的key覆盖前面的key
     * 集合无序
     */
    @Test
    public void testPutHash() {
        stringRedisTemplate.opsForHash().put("myHash", "a", "97");
        stringRedisTemplate.opsForHash().put("myHash", "b", "98");
        stringRedisTemplate.opsForHash().put("myHash", "c", "99");
        stringRedisTemplate.opsForHash().put("myHashOne", "c", "99");
        stringRedisTemplate.opsForHash().put("myHashOne", "d", "100");
        stringRedisTemplate.opsForHash().put("myHashOne", "e", "101");
        stringRedisTemplate.opsForHash().put("myHashOne", "f", "102");
    }


    @Test
    public void testGetHash() {
        String str = (String) stringRedisTemplate.opsForHash().get("myHash", "a");
        System.out.println(str);
    }

    @Test
    public void testEntriesHash() {
        //获取Map对象
        Map<Object, Object> hash = stringRedisTemplate.opsForHash().entries("myHash");
        //遍历Map对象
        for (Map.Entry<Object, Object> entry : hash.entrySet()) {
            System.out.println("key=" + entry.getKey() + "\t" + "value=" + entry.getValue());
        }
    }

    /**
     * 删除指定map对应的key元素
     */
    @Test
    public void testDeleteHash(){
        stringRedisTemplate.opsForHash().delete("myHash","b");
    }

    /**
     * 获取指定map的大小
     */
    @Test
    public void testGetSizeHash(){
        Long size = stringRedisTemplate.opsForHash().size("myHashOne");
        System.out.println(size);
    }
2.4.3 操作String
  • 增添数据
    stringRedisTemplate.opsForValue().set("A","65")
  • 获取数据
    stringRedisTemplate.opsForValue().get("B")
  • 删除数据
    stringRedisTemplate.delete("a")
	/**
     * 操作String
     * set、get、delete
     */
    @Test
    public void testSetValue(){
        stringRedisTemplate.opsForValue().set("A","65");
        stringRedisTemplate.opsForValue().set("B","66");
        stringRedisTemplate.opsForValue().set("0","30");
        stringRedisTemplate.opsForValue().set("a","97");

    }

    @Test
    public void testGetValue(){
        String s = stringRedisTemplate.opsForValue().get("B");
        System.out.println(s);
    }

    @Test
    public void testDeleteValue(){
        Boolean a = stringRedisTemplate.delete("a");
        System.out.println(a);
    }

2.4.4 操作Set集合
  • 增添数据
    stringRedisTemplate.opsForSet().add("a","97"):增添key为a的集合数据,注意,key要相同,key相当于set集合名称,v要不同,因为set集合存放的是不同元素。
  • 查询数据
    stringRedisTemplate.opsForSet().members("a"):返回Set集合,通过迭代器迭代输出。
    Iterator it = set.iterator();
    while (it.hasNext()){
        String next =(String) it.next();
        System.out.println(next);
    }
    
  • 删除数据
    stringRedisTemplate.opsForSet().remove("a","97")

作用范围:全局去重的功能

	/**
     * 操作Set集合
     */

    @Test
    public void testSet(){
        stringRedisTemplate.opsForSet().add("a","97");
        stringRedisTemplate.opsForSet().add("a","98");
        stringRedisTemplate.opsForSet().add("a","99");
        stringRedisTemplate.opsForSet().add("a","100");
    }

    @Test
    public void testGetSet(){
    	//根据key获取set中所有的值
        Set<String> set = stringRedisTemplate.opsForSet().members("a");
        System.out.println(set);
        Iterator it = set.iterator();
        while (it.hasNext()){
            String next =(String) it.next();
            System.out.println(next);
        }
    }

    @Test
    public void deleteSet(){
        stringRedisTemplate.opsForSet().remove("a","97");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值