redis使用,及整合進springboot

redis官方不支持windows,win版本的鏈接現在刪了,微軟的維護團隊16年也跑路了,現在只有這個github的存貨

https://github.com/microsoftarchive/redis/releases

linux版本的去官網下

 

一 安裝和啓動服務

win:

壓縮包解壓,在解壓目錄打開cmd,命令 redis-server.exe redis.windows.conf 啓動。關閉窗口即會關閉redis服務。

linux:

待補充

 

二 管理

win:

解壓目錄打開cmd,命令 redis-cli.exe 進入管理。

linux:

待補充

可視化:

待補充

 

三 springboot整合

1 maven添加依賴(版本需要對應,否則會衝突)

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.4.RELEASE</version>
        </dependency>

application.properties

#訪問地址
spring.redis.host=127.0.0.1
#訪問端口
spring.redis.port=6379
#注意,如果沒有password,此處不設置值,但這一項要保留
spring.redis.password=

#最大空閒數,數據庫連接的最大空閒時間。超過空閒時間,數據庫連接將被標記爲不可用,然後被釋放。設爲0表示無限制。
spring.redis.pool.max-Idle=300
spring.redis.pool.min-idle=0
#連接池的最大數據庫連接數。設爲0表示無限制
spring.redis.pool.max-active=600
#最大建立連接等待時間。如果超過此時間將接到異常。設爲-1表示無限制。
spring.redis.pool.max-Wait=1000
#連接超時時間
spring.redis.timeout=1000

2 config類

package com.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

3 工具類

package com.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private final RedisTemplate<String,Object> redisTemplate;

    public RedisService(RedisTemplate<String,Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    /*設置失效時間*/
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*獲取key的過期時間,0爲永久有效*/
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /*判斷key是否存在*/
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*刪除*/
    @SuppressWarnings("unchecked")
    public void del(String... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /*獲取*/
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    /*緩存放入*/
    public boolean set(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入並設置過期時間*/
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else{
                set(key,value);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*遞增 delta遞增加幾,需大於0*/
    public long incr(String key,long delta){
        if(delta<0){
            throw new RuntimeException("遞增因子必須大於0");
        }
        return redisTemplate.opsForValue().increment(key,delta);
    }

    /*遞減 delta遞減減幾,需大於0*/
    public long decr(String key,long delta){
        if(delta<0){
            throw new RuntimeException("遞減因子必須大於0");
        }
        return redisTemplate.opsForValue().increment(key,-delta);
    }

    /*獲得map*/
    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key,item);
    }

    /*獲取map*/
    public Map<Object,Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /*放入map*/
    public boolean hmset(String key,Map<String,Object> map){
        try {
            redisTemplate.opsForHash().putAll(key,map);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入map並設置過期時間*/
    public boolean hmset(String key,Map<String,Object> map,long time){
        try {
            redisTemplate.opsForHash().putAll(key,map);
            if(time>0){
                expire(key,time);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入map元素*/
    public boolean hset(String key,String item,Object value){
        try {
            redisTemplate.opsForHash().put(key,item,value);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入map元素並設置過期時間*/
    public boolean hset(String key,String item,Object value,long time){
        try {
            redisTemplate.opsForHash().put(key,item,value);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*刪除map中值*/
    public void hdel(String key,Object... item){
        redisTemplate.opsForHash().delete(key, item);
    }

    /*判斷map中有無*/
    public boolean hHasKey(String key,String item){
        return redisTemplate.opsForHash().hasKey(key,item);
    }

    /*hash遞增*/
    public double hincr(String key,String item,double by){
        return redisTemplate.opsForHash().increment(key,item,by);
    }

    /*hash遞減*/
    public double hdecr(String key,String item,double by){
        return redisTemplate.opsForHash().increment(key,item,-by);
    }

    /*獲取set*/
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*查詢set元素是否存在*/
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(key,value);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入set*/
    public long sSet(String key,Object... values){
        try {
            return redisTemplate.opsForSet().add(key,values);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*放入set設置過期時間*/
    public long sSetAndTime(String key,long time,Object... values){
        try {
            Long count = redisTemplate.opsForSet().add(key,values);
            if(time>0){
                expire(key,time);
            }
            return count;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*獲得set長度*/
    public long sGEtSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*移除*/
    public long setRemove(String key,Object... values){
        try {
            Long count = redisTemplate.opsForSet().remove(key,values);
            return count;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*獲取list內容*/
    public List<Object> lGet(String key,long start,long end){
        try {
            return redisTemplate.opsForList().range(key,start,end);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*獲取list長度*/
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*根據index取list元素*/
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key,index);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*放入list*/
    public boolean lSet(String key,Object value){
        try {
            redisTemplate.opsForList().rightPush(key,value);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*放入list並設置過期時間*/
    public boolean lSet(String key,Object value,long time){
        try {
            redisTemplate.opsForList().rightPush(key,value);
            if(time>0){
                expire(key,time);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*list放入list*/
    public boolean lSet(String key,List<Object> value){
        try {
            redisTemplate.opsForList().rightPushAll(key,value);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*list放入list並設置過期時間*/
    public boolean lSet(String key,List<Object> value,long time){
        try {
            redisTemplate.opsForList().rightPushAll(key,value);
            if(time>0){
                expire(key,time);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*根據index修改list元素*/
    public boolean lUpdateIndex(String key,long index,Object value){
        try {
            redisTemplate.opsForList().set(key,index,value);
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*刪除n個值爲value*/
    public long lRemove(String key,long count,Object value){
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return 0;
        }
    }

    /*有序集合添加元素*/
    public boolean zadd(String key,Object member,double score,long time){
        try {
            redisTemplate.opsForZSet().add(key,member,score);
            if(time>0){
                expire(key,time);
            }
            return true;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return false;
        }
    }

    /*返回區間內成員*/
    public Set<Object> zRangeByScore(String key,double minScore,double maxScore){
        try {
            return redisTemplate.opsForZSet().rangeByScore(key,minScore,maxScore);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*返回元素分數*/
    public Double zscore(String key,Object member){
        try {
            return redisTemplate.opsForZSet().score(key, member);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*返回元素索引*/
    public Long zrank(String key,Object member){
        try {
            return redisTemplate.opsForZSet().rank(key, member);
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }

    /*迭代有序集合*/
    public Cursor<ZSetOperations.TypedTuple<Object>> zscan(String key){
        try {
            Cursor<ZSetOperations.TypedTuple<Object>> cursor = redisTemplate.opsForZSet().scan(key, ScanOptions.NONE);
            return cursor;
        } catch (Exception e) {
            log.error("redis error: ",e);
            return null;
        }
    }
}

(工具類中的RedisTemplate需要由config類創建實例)

4 測試

...
@Autowired
private RedisService redisService;
...

...
redisService.set("a",1);
System.out.println(redisService.get("a"));
...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章