代码已测试 直接测试就可以 ,注意 实体类一定要 实现 Serializable 接口 不然会报错
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Resource//不能用 @Autowired 因为spring容器中有 这样容易找到多个 依据类型找
private RedisTemplate<String, Object> redisTemplate;
public void setObject(String key, Object value) {
setObject(key, value, null);
}
public void setObject(String key, Object value, Long timeOut) {
redisTemplate.opsForValue().set(key, value);
if (null != timeOut) {
redisTemplate.expire(key, timeOut, TimeUnit.SECONDS);
}
}
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
}