java封装 redis 操作 对象,list集合 ,json串

/**
* 功能说明:
* 功能作者:
* 创建日期:
* 版权归属:每特教育|蚂蚁课堂所有
*/
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);
}
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpggsw.html