最近自学Redis,利用springboot整合Redis存取Redis数据
下来开始吧
1.先创建一个springboot项目,添加redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.写application.properties配置文件
spring.redis.host=127.0.0.1
spring.redis.password=
#redis端口,默认6379
spring.redis.port=6379
spring.redis.pool.max-actice=3
3.编写Controller
@Controller
@RequestMapping("redis")
public class RedisStringController {
/**
* StringRedisTemplate继承了RedisTemplate。继承RedisTempalte,
* 与RedisTemplate不同的是设置了序列化策略,使用StringRedisSerializer类来
* 序列化key-value,以及List、Hash、Set。在这里,我们直接用就行了。
*/
@Autowired
private StringRedisTemplate redisClient;
@RequestMapping("setAndsave")
@ResponseBody
public String test(String para) throws Exception{
redisClient.opsForValue().set("test", para);
String str = redisClient.opsForValue().get("test");
return str;
}
@RequestMapping("getjson")
@ResponseBody
public String getJson(){
User user1 = new User();
user1.setNickname("wang");
user1.setPassword("admin");
user1.setUsername("admin");
redisClient.opsForValue().set("user", JsonUtils.objectToJson(user1));
String str = redisClient.opsForValue().get("user");
String u1 = JsonUtils.objectToJson(user1);
return str;
}
}
5.启动服务,输入地址:
http://localhost:8080/redis/setAndsave?para=14
浏览器显示结果
打开Redis
数据存入成功!
如果还想存入对象,可以这样编写一个User类,存放属性
在地址栏输入:http://localhost:8080/redis/daetjson
打开Redis对象已存入