一、创建springboot项目(采用骨架方式)
创建完成; 我们分析下pom文件中内容: 所使用到的关键依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
二、配置文件
server.port=8088
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=30000
三、使用redis
package com.example.redis.cache;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class CacheService {
@Autowired
private StringRedisTemplate redisTemplate;
private final String DEFAULT_KEY_PREFIX = "";
private final int EXPIRE_TIME = 1;
private final TimeUnit EXPIRE_TIME_TYPE = TimeUnit.DAYS;
public <K, V> void add(K key, V value) {
try {
if (value != null) {
redisTemplate
.opsForValue()
.set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("数据缓存至redis失败");
}
}
public <K, V> void add(K key, V value, long timeout, TimeUnit unit) {
try {
if (value != null) {
redisTemplate
.opsForValue()
.set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value), timeout, unit);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("数据缓存至redis失败");
}
}
public <K, SK, V> void addHashCache(K key, SK subKey, V value) {
redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value);
}
public <K, SK, V> void addHashCache(K key, SK subKey, V value, long timeout, TimeUnit unit) {
redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value);
redisTemplate.expire(DEFAULT_KEY_PREFIX + key, timeout, unit);
}
public <K, SK> Object getHashCache(K key, SK subKey) {
return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey);
}
public <K, V> V getObject(K key, Class<V> clazz) {
String value = this.get(key);
V result = null;
if (!StringUtils.isEmpty(value)) {
result = JSONObject.parseObject(value, clazz);
}
return result;
}
public <K, V> List<V> getList(K key, Class<V> clazz) {
String value = this.get(key);
List<V> result = Collections.emptyList();
if (!StringUtils.isEmpty(value)) {
result = JSONArray.parseArray(value, clazz);
}
return result;
}
public <K> String get(K key) {
String value;
try {
value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX + key);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("从redis缓存中获取缓存数据失败");
}
return value;
}
public void delete(String key) {
redisTemplate.delete(key);
}
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
}
1、添加字符串到redis
@Test
void add() {
cacheService.add("test", 1234);
}
结果:
2、将对象转换成jsonString并存入redis
@Test
void addObject() {
User user = User.builder()
.id(ID)
.name("小萌")
.age(AGE)
.build();
cacheService.add(user.getId(), user);
}
结果:
3、将对象集合转换成jsonString,并设置过期时间存入至redis
@Test
void addObjects() {
ArrayList<User> users = new ArrayList<>();
User user = User.builder()
.id(ID)
.name("小萌")
.age(AGE)
.build();
users.add(user);
cacheService.add("key", users, 1, TimeUnit.HOURS);
}
结果:
4、获取对象
@Test
void getObject() {
User object = cacheService.getObject(ID, User.class);
System.out.println("object = " + object);
}
结果:
object = User(id=123, name=小萌, age=12)
5、获取对象集合
@Test
void getObjects() {
List<User> users = cacheService.getList("key", User.class);
System.out.println("users = " + users);
}
结果:
users = [User(id=123, name=小萌, age=12)]
6、添加 hash-set
@Test
void addHashCache() {
cacheService.addHashCache("hashKey", "key", "value");
}
结果:
7、获取 hash-setvalue
public <K, SK> Object getHashCache(K key, SK subKey) {
return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey);
}
结果:
hashCache = value
|