Springboot基础之RedisUtils工具类

SpringBoot整合Redis

引入Redis依赖

 <!-- redis-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

设置Redis的Template

RedisConfig.java

package cn.wideth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 编写配置类,构造RedisTemplate
 * 这个springboot已经帮我们配了,
 * 但是默认object,我想改成string
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        // 设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // 设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }

}

设置Redis连接信息

redis操作5种常见的数据类型

Redis工具类

redisTemplate API

1.opsForValue -> String

2.opsForSet -> Set

3.opsForHash -> hash

4.opsForZset -> SortSet

5.opsForList -> list队列

代码

package cn.wideth.util.other;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static double size = Math.pow(2, 32);

    /**
     * 写入缓存
     * @param key
     * @param offset 位 8Bit=1Byte
     * @return
     */
    public boolean setBit(String key, long offset, boolean isShow) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.setBit(key, offset, isShow);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param offset
     * @return
     */
    public boolean getBit(String key, long offset) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            result = operations.getBit(key, offset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<String, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        redisTemplate.opsForValue();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    //第一次加载的时候将数据加载到redis中
    public void saveDataToRedis(String name) {
        double index = Math.abs(name.hashCode() % size);
        long indexLong = new Double(index).longValue();
        boolean availableUsers = setBit("availableUsers", indexLong, true);
    }

    //第一次加载的时候将数据加载到redis中
    public boolean getDataToRedis(String name) {

        double index = Math.abs(name.hashCode() % size);
        long indexLong = new Double(index).longValue();
        return getBit("availableUsers", indexLong);
    }

    /**
     * 有序集合获取排名
     * @param key 集合名称
     * @param value 值
     */
    public Long zRank(String key, Object value) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rank(key,value);
    }

    /**
     * 有序集合获取排名
     * @param key
     */
    public Set<ZSetOperations.TypedTuple<Object>> zRankWithScore(String key, long start,long end) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<Object>> ret = zset.rangeWithScores(key,start,end);
        return ret;
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     */
    public Double zSetScore(String key, Object value) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.score(key,value);
    }

    /**
     * 有序集合添加分数
     * @param key
     * @param value
     * @param scoure
     */
    public void incrementScore(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.incrementScore(key, value, scoure);
    }

    /**
     * 有序集合获取排名
     * @param key
     */
    public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithScore(String key, long start,long end) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeByScoreWithScores(key,start,end);
        return ret;
    }

    /**
     * 有序集合获取排名
     * @param key
     */
    public Set<ZSetOperations.TypedTuple<Object>> reverseZRankWithRank(String key, long start, long end) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<Object>> ret = zset.reverseRangeWithScores(key, start, end);
        return ret;
    }

}

到此这篇关于Springboot基础之RedisUtils工具类的文章就介绍到这了,更多相关RedisUtils工具类内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot实现后台上传图片(工具类)

    本文实例为大家分享了springboot实现后台上传图片的具体代码,供大家参考,具体内容如下 1.先配置启动类 继承WebMvcConfigurer 重写方法 @SpringBootApplication //@MapperScan("com.example.demo.Mapper") public class DemoApplication implements WebMvcConfigurer { public static void main(String[] args) { S

  • SpringBoot Test类注入失败的解决

    如下所示 本来 bookService的引用一直是null. 导致每次测试都报空指针异常. 然后现在继承相应的 ApplicationTests类,然后使用@Component将该类注册为组件.就可以正常注入了. 补充:关于springboot test @Mapper ,@Autiwired注入无效的问题 @SpringBootTest() @RunWith(SpringRunner.class) public class ProductMapperTest { @Autowired Prod

  • springboot封装JsonUtil,CookieUtil工具类代码实例

    这篇文章主要介绍了springboot封装JsonUtil,CookieUtil工具类过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 JsonUtil public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); public static String objectToString(Object object) throws

  • springboot日志切面通用类实例详解

    1.pom.xml文件导入AOP依赖 <!--aop依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.3.0.RELEASE</version> </dependency> 2.pom.xml导入Lombo

  • springboot 获取工具类bean过程详解

    这次的实践经验的起因在于,在开发中,我想在工具类中使用配置文件的变量值.通常使用@value注解,这个只能在spring中管理的bean总获取.之前我也很疑惑,为什么之前的开发人员会在SpringUtil类上加入@Component注解,今天又遇到这种情况,其原因完全理解了. @Component public class SpringUtil implements EnvironmentAware { private static Environment env; public static

  • Springboot实现多线程注入bean的工具类操作

    场景: 使用springboot多线程,线程类无法自动注入需要的bean 解决方法: 通过工具类获取需要的bean 工具类代码: import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springfram

  • 三分钟带你了解SpringBoot真正的启动引导类

    引言 SpringBoot项目中的启动类,一般都是XXApplication,例如**「StatsApplication」,「UnionApplication」**. 每个项目的启动类名称都不一样.但是它的启动类真的是XXApplication吗? **META-INF/**Manifest.mf文件 jar文件实际上是class文件的zip压缩存档.jar并不能表达应用程序的便签信息. 「META-INF/Manifest.mf文件提供存档的便签信息.」 Manifest.mf有 「Main-

  • 浅谈HBase在SpringBoot项目里的应用(含HBaseUtil工具类)

    背景: 项目这两个月开始使用HBase来读写数据,网上现成的HBase工具类要么版本混杂,要么只是Demo级别的简单实现,各方面都不完善: 而且我发现HBase查询有很多种方式,首先大方向上有 Get 和 Scan两种,其次行键.列族.列名(限定符).列值(value).时间戳版本等多种组合条件,还有各种过滤器的选择,协处理器的应用,所以必须根据自己项目需求和HBase行列设计来自定义HBase工具类和实现类! 经过我自己的研究整理,在此分享下初步的实现方案吧 ~ 注:HBase版本:1.3.0

  • 兼容Spring Boot 1.x和2.x配置类参数绑定的工具类SpringBootBindUtil

    为了让我提供的通用 Mapper 的 boot-starter 同时兼容 Spring Boot 1.x 和 2.x,增加了这么一个工具类. 在 Spring Boot 中,能够直接注入 XXProperties 类的地方不需要使用这个工具类. 但是在Spring 的接口和启动流程设计中,有些情况下只能通过EnvironmentAware接口得到Environment对象,此时你想得到 XXProperties 类没有更好的办法. 也许有人直接从Environment 对象中遍历获取所有的配置信

  • SpringBoot使用validation-api实现对枚举类参数校验的方法

    前言 之前写了一个博客是关于使用SpringBoot使用validation-api实现参数校验,当时使用的注解都是validation-api自带的注解只能完成对空值.长度等简单的校验,在我们日常的使用当中会遇到对参数是否在枚举值类的校验,针对这种情况我们怎么来实现呢? SpringBoot使用validation-api实现参数校验可参考我的博客:SpringBoot使用validation-api实现参数校验 正文 SpringBoot使用validation-api实现对枚举类参数校验

随机推荐