1、pom.xml文件里面增加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、yml文件增加如下配置:
redis:
host: localhost
port: 6379
password: heming
database: 10
配置结构如下图所示:?
3、新增RedisConfiguration.java类
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
log.info("开始创建redis模板对象...");
RedisTemplate redisTemplate = new RedisTemplate();
//设置redis的连接工厂对象
redisTemplate.setConnectionFactory(redisConnectionFactory);
//设置redis key的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}
?4、新增RedisTestController.java类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
@Slf4j
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;
/**
* redis test
* @return
*/
@GetMapping(value = "/redisTest")
public void getGirlList(){
log.info("bbbbb");
redisTemplate.opsForValue().set("name","小明"); // 设置k v
String city = (String) redisTemplate.opsForValue().get("name"); // 拿到key为name的值
System.out.println(city);
redisTemplate.opsForValue().set("code","1234",1, TimeUnit.MINUTES); // 设置过期时间为三分钟
redisTemplate.opsForValue().setIfAbsent("lock","1"); // 设置lock为k的唯一值
redisTemplate.opsForValue().setIfAbsent("lock","2");
}
}
4、验证
浏览器直接访问GET接口
http://localhost:8081/redisTest
然后查看数据
发现有乱码,怎么处理??