spring boot使用redis
2024-05-28更新
推荐使用这个工具实现操作redis:https://doc.hutool.cn
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等各种序列号工具序列化和反序列化
本文来自博客园,作者:小枫同学,除网络转载的部分,其他版权属于作者和博客园所有,未经作者或博客园许可,禁止转载、复制、重新发布完整或者部分文字、代码、图片等信息,否则将保留追究法律责任的权利(如博客侵权了您的作品,本人再次表示抱歉,请将原创地址发送至下文邮箱,核实后立刻删除。)。查阅文章的同学,由于网络爬虫严重,有些代码并不会完整贴出来或者存在bug,不过你可以发送邮件到xfstune@126.com获取新代码,记得附上文章链接