微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

redis

package com.ekgc.medial.base.util;

import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedistemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <b>Redis 操作工具类</b>
 * @author Arthur
 * @version 3.0.0
 */
@Component("redisUtil")
public class RedisUtil {
	@Autowired
	private StringRedistemplate redistemplate;

	/**
	 * <b>将对象存储到 Redis 中</b>
	 * @param key
	 * @param value
	 * @param expireTimeSeconds
	 * @return
	 */
	public  boolean savetoRedis(String key, Object value, Long expireTimeSeconds) {
		try {
			// 将用户所给定的 Object 类型的 value 变为 String 类型的 JSON
			JsonMapper jsonMapper = new JsonMapper();
			String valueJSON = jsonMapper.writeValueAsstring(value);
			// 将该 JSON 存储到 Redis 中
			redistemplate.opsForValue().set(key, valueJSON);
			// 设置过期时间
			redistemplate.expire(key, expireTimeSeconds, TimeUnit.SECONDS);
			return true;
		} catch (Exception e) {
			e.printstacktrace();
		}
		return false;
	}

	/**
	 * <b>根据 Key 获得存储的对象信息</b>
	 * @param key
	 * @param type
	 * @return
	 */
	public  Object getFromredis(String key, Class type) {
		try {
			// 通过 key 从 Redis 中获得对应 JSON
			String valueJSON = redistemplate.opsForValue().get(key);
			// 判断此时能够获取到对应的 JSON
			if (valueJSON != null && !"".equals(valueJSON)) {
				// 此时存在对应的信息,那么变为对象
				JsonMapper jsonMapper = new JsonMapper();
				Object obj = jsonMapper.readValue(valueJSON, type);
				return obj;
			}
		} catch (Exception e) {
			e.printstacktrace();
		}
		return null;
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐