spring boot使用redis

发布时间 2023-10-24 11:41:22作者: 小枫同学

0x01依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

0x02配置

#application.yml
spring:
  data:
    redis:
      host: 127.0.0.1
      port: 6379
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          max-wait: 2000

0x03简单封装(这里篇幅限制,可以搜索stringRedisTemplate的各种操作类的方法,自己封装)

package com.xx.xx.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class Redis {

    private final StringRedisTemplate stringRedisTemplate;

    private static  final ObjectMapper mapper=new ObjectMapper();

    public Redis(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * Sets the value of a key in the Redis cache.
     *
     * @param  key   the key to set
     * @param  value the value to set for the key
     * @param  time  the expiration time in seconds
     */
    public void set(String key,String value,Long time){
        stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
    }

    /**
     * Retrieves the value associated with the specified key from the Redis database.
     *
     * @param  key  the key to retrieve the value for
     * @return      the value associated with the specified key, or null if the key does not exist
     */
    public String get(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    /*
     * Deletes the value associated with the specified key from the Redis database
     * @param  key  the key to delete
     */
    public void del(String key){
        stringRedisTemplate.delete(key);
    }
}

0x04使用

package com.xx.main;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.xx.common.utils.Redis;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class XfstuApplicationTests {

    @Autowired
    private Redis redis;

    private static final ObjectMapper mapper=new ObjectMapper();

    @Test
    void contextLoads() {
    }

    @Test
    void test() {
        System.out.println(redis.get("key"));
    }
}

0x05 注意事项

  • 需要存储对象等,自己使用JSON等各种序列号工具序列化和反序列化