SpringBootはredisと簡単なツールクラスを統合して使用します

7466 ワード

この記事は単にSpringBootがredisとredisを統合する単純なツールクラスにすぎない
1.pomファイルのインポート


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

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 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 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 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 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 value) {
        boolean result = false;
        try {
            redisTemplate.opsForHash().putAll(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public  Map hmget(String key) {
        Map 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 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 obj = redisUtil.hmget("mapHot");
        if(obj==null){
            Map mapHot = new HashMap();
            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 "     ";
    }
}