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

将redis工具封装成springboot的start

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

将redis工具封装成springboot的start

项目结构:

 pom.xml引用



    4.0.0
    
        com.example
        platform-demo
        0.0.1-SNAPSHOT
    
    com.example
    redis-client
    0.0.1-SNAPSHOT
    redis-client
    redis-client
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


RedisBloom

package com.example.redisclient.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;


@Component
public class RedisBloom {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static RedisScript bfreserveScript = new DefaultRedisScript<>("if redis.call('bf.reserve', KEYS[1], ARGV[1], ARGV[2]) then return true else return false end", Boolean.class);

    private static RedisScript bfaddScript = new DefaultRedisScript<>("return redis.call('bf.add', KEYS[1], ARGV[1])", Boolean.class);

    private static RedisScript bfexistsScript = new DefaultRedisScript<>("return redis.call('bf.exists', KEYS[1], ARGV[1])", Boolean.class);

    private static String bfmaddScript = "return redis.call('bf.madd', KEYS[1], %s)";

    private static String bfmexistsScript = "return redis.call('bf.mexists', KEYS[1], %s)";

    
    public Boolean bfreserve(String key, double errorRate, int initialSize){
        Boolean create = false;
        try {
            create = redisTemplate.execute(bfreserveScript, Arrays.asList(key), errorRate+"", initialSize+"");
        }catch (Exception e){
            if (e.getMessage().contains("ERR item exists")){
                System.out.println("过滤器已经存在");
            }

        }
        return create;
    }

    
    public Boolean bfadd(String key, String value){
        return redisTemplate.execute(bfaddScript, Arrays.asList(key), value);
    }

    
    public Boolean bfexists(String key, String value){
        return redisTemplate.execute(bfexistsScript, Arrays.asList(key), value);
    }

    
    public List bfmadd(String key, String... values){
        return (List)redisTemplate.execute(this.generateScript(bfmaddScript, values), Arrays.asList(key), values);
    }

    
    public List bfmexists(String key, String... values){
        return (List)redisTemplate.execute(this.generateScript(bfmexistsScript, values), Arrays.asList(key), values);
    }

    private RedisScript generateScript(String script, String[] values) {
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= values.length; i ++){
            if(i != 1){
                sb.append(",");
            }
            sb.append("ARGV[").append(i).append("]");
        }
        return new DefaultRedisScript<>(String.format(script, sb.toString()), List.class);
    }

}

RedisLock

package com.example.redisclient.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Collections;

@Component
public class RedisLock {
    @Autowired
    private StringRedisTemplate redisTemplate;

    
    public Boolean lock(String key,String value,Long time){
        Boolean lockStatus = redisTemplate.opsForValue().setIfAbsent(key,value, Duration.ofSeconds(time));
        return lockStatus;
    }

    
    public Long unLock(String key,String value){
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript redisScript = new DefaultRedisScript<>(luaScript,Long.class);
        Long releaseStatus = redisTemplate.execute(redisScript, Collections.singletonList(key),value);
        return releaseStatus;
    }
}

RedisUtil

package com.example.redisclient.util;

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

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    
    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

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

    
    public void setRange(String key, Object value,long offset) {
        redisTemplate.opsForValue().set(key,value,offset);
    }

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

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

    
    public Long del(List keys) {
        return redisTemplate.delete(keys);
    }

    
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    
    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    
    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    
    public Map hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public Boolean hSetAll(String key, Map map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    
    public void hSetAll(String key, Map map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    
    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    
    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    
    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    
    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    
    public Set sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    
    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    
    public Long sAdd(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    
    public List lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    
    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    
    public Long lPush(String key, Object value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }

    
    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    
    public Long lPushAll(String key, Long time, Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }

    
    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }

    
    public void incrCount(String key, long time){
        Long increment = redisTemplate.opsForValue().increment(key);
        if(increment.intValue()==1){
            this.set(key,increment,time);
        }else {
            this.setRange(key,increment,0);
        }
    }

}
 

 RedisClientAutoConfig

package com.example.redisclient.config;

import com.example.redisclient.util.RedisBloom;
import com.example.redisclient.util.RedisLock;
import com.example.redisclient.util.RedisUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisClientAutoConfig {
    @Bean
    @ConditionalOnMissingBean    //默认的bean类型,具体的Conditional注解还有很多,有兴趣自己玩玩
    public RedisLock redisLock(){
        return new RedisLock();
    }
    @Bean
    public RedisBloom redisBloom(){
        return new RedisBloom();
    }
    @Bean
    public RedisUtil redisUtil(){
        return new RedisUtil();
    }
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //key序列化
        redisTemplate.setKeySerializer(redisSerializer);
        //value序列化
        redisTemplate.setValueSerializer(redisSerializer);
        //value hashmap序列化
        redisTemplate.setHashKeySerializer(redisSerializer);
        //key hashmap序列化
        redisTemplate.setHashValueSerializer(redisSerializer);
        return redisTemplate;
    }
}

打包

resources下新建META-INF目录,新建spring.factories文件

 pring.factories内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.example.redisclient.config.RedisClientAutoConfig

sms项目引用redis-client

 封装类的使用

@Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisBloom redisBloom;
    @Autowired
    private RedisLock redisLock;

    
    public void test(){
        redisBloom.bfadd("key","value");
        redisBloom.bfexists("key","value");
        redisLock.lock("key","value",5L);
        redisLock.unLock("key","value");
        redisUtil.set("key","value");
        redisUtil.get("key");
    }

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

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

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