栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot结合Redis实现工具类的方法示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring boot结合Redis实现工具类的方法示例

自己整理了 spring boot 结合 Redis 的工具类

引入依赖


  org.springframework.boot
  spring-boot-starter-data-redis

加入配置

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379

实现代码

这里用到了 静态类工具类中 如何使用 @Autowired

package com.lmxdawn.api.common.utils;

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

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Component
public class CacheUtils {
  @Autowired
  private RedisTemplate redisTemplate;

  // 维护一个本类的静态变量
  private static CacheUtils cacheUtils;

  @PostConstruct
  public void init() {
    cacheUtils = this;
    cacheUtils.redisTemplate = this.redisTemplate;
  }

  
  public static void set(String key, String value) {
    cacheUtils.redisTemplate.opsForValue().set(key, value);
  }

  
  public static void set(String key, String value, Long timeout) {
    cacheUtils.redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
  }

  
  public static Object get(String key) {
    return cacheUtils.redisTemplate.opsForValue().get(key);
  }

  
  public static boolean expire(String key, Long ttl) {
    return cacheUtils.redisTemplate.expire(key, ttl, TimeUnit.SECONDS);
  }

  
  public static boolean hasKey(String key) {
    return cacheUtils.redisTemplate.hasKey(key);
  }

  
  public static Long sAdd(String key, String... value) {
    return cacheUtils.redisTemplate.opsForSet().add(key, value);
  }

  
  public static Set sGetMembers(String key) {
    return cacheUtils.redisTemplate.opsForSet().members(key);
  }

  
  public static Boolean zAdd(String key, String value, double score) {
    return cacheUtils.redisTemplate.opsForZSet().add(key, value, score);
  }

  
  public static Double zScore(String key, String value) {
    return cacheUtils.redisTemplate.opsForZSet().score(key, value);
  }

  
  public static Boolean delete(String key) {
    return cacheUtils.redisTemplate.delete(key);
  }

  
  public static Long delete(Collection keys) {
    return cacheUtils.redisTemplate.delete(keys);
  }
}

相关地址

GitHub 地址:https://github.com/lmxdawn/vue-admin-java

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139613.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号