导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
使用restful风格 string、list、hash、set、zset同理
实体类
/**
* 向缓存中存入对象是必须将对象进行序列化 否则无法完成存储
*/
@Data
public class User implements Serializable {
private Integer uid;
private String uname;
private String upwd;
}
Controller类
@RestController
public class UserController {
@Autowired
private RedisTemplate redisTemplate;
/**
* 使用@RequstBody注解可以接受json字符串转化成对象
* @param user
*/
@PostMapping("/set")
public void set(@RequestBody User user){
redisTemplate.opsForValue().set("user",user);
}
@GetMapping("/get/{key}")
public User get(@PathVariable("key") String key){
return (User) redisTemplate.opsForValue().get("key");
}
@DeleteMapping("/delete/{key}")
public void delete(@PathVariable("key") String key){
redisTemplate.delete(key);
}
}
yml配置文件
spring:
redis:
host: localhost
database: 0
port: 6379
postman操作如下:
set存入
get取出
set成功后 在客户端命令行中 直接 get key 是获取不到的
因为 set成功后 redis会在key前面加上特殊的处理 在value上也会添加同样的处理
自定义工具类
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
RedisUtils
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate){
this.redisTemplate = redisTemplate;
}
/**
* 指定缓存的失效时间
* @param key redis中的键
* @param time 时间(秒)
* @return 该key对应的值是否失效
*/
public boolean expire(String key, long time){
try {
if (time > 0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 根据key拿到该key的失效时间
* @param key
* @return 失效时间(秒)
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否在redis中存在
* @param key 值
* @return true存在,否则false
*/
public boolean hasKey(String key){
return redisTemplate.hasKey(key);
}
/**
* 删除缓存中所有的keys的值
* @param keys 可变长度的参数,可以是0个,1个和多个key进行删除
*/
public void delete(String ... keys){
if (keys != null && keys.length > 0){
if(keys.length == 1){
redisTemplate.delete(keys[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(keys));
}
}
}
//String类型
/**
* 获取string类型的key对应的值
* @param key String类型redis数据的key
* @return 该key对应的String的value值
*/
public Object get(String key){
return key == null ? null: redisTemplate.opsForValue().get(key);
}
/**
*在redis服务器中放置String类型的值
* @param key String类型的key
* @param value,值
* @return true添加成功,否则false
*/
public boolean set(String key, Object value){
try {
redisTemplate.opsForValue().set(key, value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 在redis服务器中放置String类型的值,并设置失效时间
* @param key String类型的key
* @param value 值
* @param time 失效时间(秒)
* @return
*/
public boolean set(String key, Object value, long time){
try {
if(time > 0)
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
else
set(key, value);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
//String类型
//hash类型
/**
* hash类型数据的存储
* @param key hash类型值的key
* @param map 键值对
* @return
*/
public boolean hmset(String key, Map<String, Object> map){
try{
redisTemplate.opsForHash().putAll(key, map);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* 设置hash中指定key下的field的值为value
* @param key hash的key键
* @param field hash中的field域
* @param value 给hash中的field设置的值
* @return true设置成功,否则false
*/
public boolean hset(String key, String field, Object value){
try {
redisTemplate.opsForHash().put(key, field, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 设置hash中指定key下的field的值为value,并设置失效时间
* @param time 失效时间
* @param key hash的key键
* @param field hash中的field域
* @param value 给hash中的field设置的值
* @return true设置成功,否则false
*/
public boolean hset(String key, String field, Object value, long time){
try {
redisTemplate.opsForHash().put(key, field, value);
if (time > 0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* hash类型数据的存储
* @param key hash类型值的key
* @param map 键值对
* @param time 失效时间
* @return true代表设置成功,否则false
*/
public boolean hmset(String key, Map<String, Object> map, long time){
try{
redisTemplate.opsForHash().putAll(key, map);
if(time > 0){
expire(key, time);
}
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
/**
* hash类型数据的获取
* @param key hash类型数据的键
* @param field hash类型的field
* @return 在该key所对应的hash中field的值
*/
public Object hget(String key, String field){
return redisTemplate.opsForHash().get(key, field);
}
/**
* 获取hash类型数据的key对应的整个map对象
* @param key hash中的key
* @return 该hash key对应的hash对象
*/
public Map<Object, Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
}
RedisConfig.java
@Configuration
@ConditionalOnClass(RedisProperties.class)
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> template = new RedisTemplate<>();
//使用fastjson实现对于对象的序列化
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
//设置值的序列号方式
template.setValueSerializer(serializer);
//设置key的序列化方式
template.setKeySerializer(serializer);
//设置hash值的序列化方式
template.setHashValueSerializer(serializer);
//设置hash的key的序列化方式
template.setHashKeySerializer(serializer);
//设置redis模板的工厂对象
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
测试类
@SpringBootTest
public class TestRedisUtil {
@Resource
private RedisUtil utils;
@Test
public void testString() throws InterruptedException {
System.out.println(utils.set("hello11", "world11"));
System.out.println(utils.get("hello11"));
System.out.println(utils.set("1", "1", 5));
System.out.println(utils.get("1"));
Thread.sleep(5000);
System.out.println(utils.get("1"));
}
@Test
public void testStringObject() throws InterruptedException {
User user = new User();
user.setUid(9527);
user.setUsername("zhouxingxing");
user.setPassword("999999");
user.setAge(20);
System.out.println(utils.set("zhouxing", user, 5));
System.out.println(utils.get("zhouxing"));
Thread.sleep(5000);
System.out.println(utils.get("zhouxing"));
}
@Test
public void testStringList(){
List<User> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new User(i, "name" + i, "pass" + i, 18 + i));
}
System.out.println(utils.set("list", list));
utils.get("list");
}
@Test
public void testHash(){
Map<String, Object> users = new HashMap<>();
users.put("wukong", "sunxingzhe");
User tangtang = new User(1000, "tangsanzang", "888888", 20);
users.put("tangtang", tangtang);
users.put("bajie", "zhuwunong");
System.out.println(utils.hmset("xiyouji", users));
System.out.println(utils.hmget("xiyouji"));
System.out.println(utils.hget("xiyouji", "tangtang"));
}
}