springboot 整合redis,操作工具类,对象,集合list。

完整项目地址 https://gitee.com/javawxc/springboot2.0-redis

主要是看看redis封装操作类,可以操作json、对象,集合list,

/**
* 功能说明:
* 功能作者:
* 创建日期:
* 版权归属:每特教育|蚂蚁课堂所有 www.itmayiedu.com
*/
package com.redis.service;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import ch.qos.logback.core.util.TimeUtil;

// springboot 2.0 整合redis
@Component
public class RedisService {

@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<Object,Object> template;


public void set(String key, Object object, Long time) {
// 让该方法能够支持多种数据类型存放
// 如果存放时Set类型
if (object instanceof Set) {
setSet(key, object);
}
setString(key,object);


// 设置有效期

if (time != null) {
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}

}



public void setString(String key, Object object) {
String value = toJson(object);
// 存放string类型
stringRedisTemplate.opsForValue().set(key, value);
}
public void setMap(String key,Object object){
Map value=(Map) object;
stringRedisTemplate.opsForValue().multiGet((Collection<String>) value);
}


public void setSet(String key, Object object) {
Set<String> valueSet = (Set<String>) object;
for (String string : valueSet) {
stringRedisTemplate.opsForSet().add(key, string);
}
}

public String getString(String key) {
System.out.println("获取的数据格式是"+stringRedisTemplate.opsForValue().get(key) ) ;
return stringRedisTemplate.opsForValue().get(key);
}
/**
* Object转成JSON数据
*/
private String toJson(Object object){
if(object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String){
return String.valueOf(object);
}
System.out.println("存入的数据格式是"+JSON.toJSONString(object));
return JSON.toJSONString(object);
}

public <T> T fromJson(String json, Class<T> clazz){
return JSON.parseObject(json, clazz);
}
}
posted @ 2019-08-13 17:44  向上生长6688  阅读(1684)  评论(0编辑  收藏  举报