1. 程式人生 > >SpringBoot整合redis及簡單工具類使用

SpringBoot整合redis及簡單工具類使用

本篇文章只是簡單的SpringBoot整合redis及redis的簡單工具類

1.匯入pom檔案

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

2.application.properties

# redis (RedisProperties)
# Redis資料庫索引(預設為0)
spring.redis.database=10
# Redis伺服器地址
spring.redis.host=192.168.1.103
# Redis伺服器連線埠
spring.redis.port=6379
# Redis伺服器連線密碼(預設為空)
spring.redis.password=
# 連線池最大連線數(使用負值表示沒有限制)
spring.redis.pool.max-active=-1
# 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連線池中的最大空閒連線
spring.redis.pool.max-idle=8
# 連線池中的最小空閒連線
spring.redis.pool.min-idle=0
# 連線超時時間(毫秒)
spring.redis.timeout=100

3.RedisUtil工具類

package com.example.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by 李慶偉 on 2018/10/15.
 */
@SuppressWarnings("unchecked")
@Component
public class RedisUtil {

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 批量刪除對應的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
    /**
     * 批量刪除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
    /**
     * 刪除對應的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 String get(final String key) {
        Object result = null;
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        if(result==null){
            return null;
        }
        return result.toString();
    }
    /**
     * 寫入快取
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, 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<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public  boolean hmset(String key, Map<String, String> value) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public  Map<String,String> hmget(String key) {
        Map<String,String> result =null;
        try {
            result=  redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

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

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

    /**
     * redis zset可已設定排序(案例,熱搜)
     *
     * @param key 鍵
     * @paramby
     * @return
     */
    public void zadd(String key ,String name) {
        BoundZSetOperations<Object, Object> boundZSetOperations = redisTemplate.boundZSetOps(key);
        //自增長後的資料
        boundZSetOperations.incrementScore(name,1);
    }

}

4.測試

package com.example.demo.controller;
import com.example.demo.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 李慶偉 on 2018/7/24.
 */
@RequestMapping("/redisUtil")
@RestController
public class RedisController {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * redis新增測試
     * @param redisKey
     * @param redisValue
     */
    @RequestMapping("addRedis")
    @ResponseBody
    public String addRedis(String redisKey,String redisValue){
        redisUtil.set(redisKey,redisValue);
        return "addRedis新增redis資料成功";
    }

    /**
     * redis key獲取value測試
     * @param redisKey
     */
    @RequestMapping("getValueByRedis")
    @ResponseBody
    public String getValueByRedis(String redisKey){
        Object obj = redisUtil.get(redisKey);
        if(obj!=null){
            System.out.print((String) obj);
            return (String) obj;
        }else {
            return null;
        }
    }

    /**
     * 案例1
     * 可以增加熱搜,但是在取熱搜詞的時候,Map排序問題
     *
     * redis key獲取value測試   模擬熱搜 增加1
     * @param hotWord
     */
    @RequestMapping("updateValueByHotWord")
    @ResponseBody
    public String updateValueByHotWord(String hotWord){
        Map<String,String> obj = redisUtil.hmget("mapHot");
        if(obj==null){
            Map<String ,String> mapHot = new HashMap<String ,String>();
            mapHot.put(hotWord,"1");
            redisUtil.hmset("mapHot",mapHot);
        }else {
            if(obj.get(hotWord)==null){
                obj.put(hotWord,"1");
            }else {
                obj.put(hotWord,Integer.parseInt(obj.get(hotWord))+1+"");
            }
            redisUtil.hmset("mapHot",obj);
        }

        return "熱搜已更新";
    }
}