版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dengqiang123456/article/details/78941354
一、添加jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、添加 redis配置
#redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456
spring.redis.database=0
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.timeout=0
三、添加工具类
package com.drunck.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void set(String key, String value) {
this.stringRedisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return this.stringRedisTemplate.opsForValue().get(key);
}
public void del(String key) {
this.stringRedisTemplate.delete(key);
}
}
四、使用
if(CommonUtil.isNotEmpty(redisUtil)) {
System.out.println(redisUtil.get("key"));
} else {
redisUtil.set("key", "redis");
}