1、添加依赖
pom.xml:
<!-- 整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、Redis配置
application.properties:
spring.redis.host=localhost
spring.redis.port=6379
#会有分区,默认是0
#spring.redis.database=
#spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1ms
spring.redis.jedis.pool.max-idle=500
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=5000ms
3、Controller业务
这里使用Springboot提供的RedisTemplate对Redis进行相关操作:
package com.lzz.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class indexController {
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/setString")
public String setString(){
ValueOperations ops = redisTemplate.opsForValue();
ops.set("test","2");
return "DONE";
}
@RequestMapping("/getString")
public String getString(){
ValueOperations<String,String> ops= redisTemplate.opsForValue();
return ops.get("test");
}
}
RedisTemplate介绍
spring 封装了 RedisTemplate
RedisTemplate中定义了对5种数据结构操作
- redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForList();//操作list
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作sortSet,有序set
StringRedisTemplate与RedisTemplate
spring 同时提供StringRedisTemplate,在键值对都是String类型时推荐使用StringRedisTemplate进行操作;虽然StringRedisTemplate继承RedisTemplate,但是它们管理是数据是不互通的。此外:
- SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
- StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
- RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
两种策略进行序列化会有一定的不同:
JDK的序列化策略是将其key和value保存成字节数组;String则是存储为字符串;通过命令或管理工具查看时,看起来会是乱码。