二、在java中使用redis

(一)添加POM依赖

    <!-- redis驱动 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- redis池 -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.6.RELEASE</version>
        </dependency>
        <!-- 这个依赖用于解决json中文乱码使用(好神奇) -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.5.0</version>
        </dependency>

(二)编写配置文件

    <!--redis数据源-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大空闲数-->
        <property name="maxIdle" value="300"/>
        <!--最大空连接数-->
        <property name="maxTotal" value="1024"/>
        <!--最大等待时间-->
        <property name="maxWaitMillis" value="1000"/>
        <!--连接超时时是否阻塞,false时报异常,true阻塞直到超时,默认为true-->
        <property name="blockWhenExhausted" value="true"/>
        <!--返回连接时,检测连接是否成功-->
        <property name="testOnBorrow" value="true"/>
    </bean>
    <!-- Spring-redis连接池管理工厂 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost"/>
        <property name="port" value="6379"/>
        <property name="password" value=""/>
        <!--超时时间 默认2000-->
        <property name="timeout" value="100000"/>
        <!--连接池配置-->
        <property name="poolConfig" ref="jedisPoolConfig"/>
        <!--是否使用连接池-->
        <property name="usePool" value="true"/>
    </bean>

    <!--redis模板   start-->
    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="keySerializer" ref="stringRedisSerializer"/>
        <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>
        <property name="hashKeySerializer" ref="stringRedisSerializer"/>
        <property name="hashValueSerializer" ref="jdkSerializationRedisSerializer"/>
        <!--开启事务  -->
        <property name="enableTransactionSupport" value="true"/>
    </bean>
    <!--redis模板   end-->

(三)封装redis接口

package org.pc.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

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

/**
 * @author 咸鱼
 * @date 2018/7/1 14:59
 */
public final class RedisUtils {
    private RedisTemplate<String, Object> redisTemplate;

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

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 失效时间
     * @return <code>true:</code>设置成功,<code>false:</code>设置失败
     */
    public boolean expire(String key, long time){
        try {
            if (time > 0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键
     * @return 时间(秒) 返回0代表永久有效
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return <code>true:</code>存在,<code>false:</code>不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 删除缓存
     * @param keys 可以一个或多个键值
     */
    @SuppressWarnings("unchecked")
    public void delete(String... keys){
        if (keys != null && keys.length > 0){
            if (keys.length == 1){
                redisTemplate.delete(keys[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(keys));
            }
        }
    }

    /*=============================String start================================*/
    /**
     * 普通缓存获取
     * @param key 键
     * @return 缓存的对象
     */
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     *
     * @param key 键
     * @param value 值
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean set(String key, Object value){
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param timeout 时间(秒) 若小于0,则代表永久有效
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean set(String key, Object value, long timeout){
        try {
            if (timeout > 0){
                redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return 自增后的键
     */
    public long increment(String key, long delta) {
        if (delta < 0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(大于0)
     * @return 自减后的键
     */
    public long decrement(String key, long delta) {
        if (delta < 0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    /*=============================Map start================================*/

    /**
     * HashGet(Hash值的形式是:key  [{field,value}, {field1,value1}.....])
     * @param key 键 不能为null
     * @param hashKey 项 不能为null
     * @return 值
     */
    public Object hGet(String key, String hashKey){
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param hashKey 哈希键
     * @param value 值
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean hSet(String key, String hashKey, Object value){
        try {
            redisTemplate.opsForHash().put(key, hashKey, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param hashKey 哈希键
     * @param value 值
     * @param timeout 过期时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean hSet(String key, String hashKey, Object value, long timeout){
        try {
            redisTemplate.opsForHash().put(key, hashKey, value);
            expire(key, timeout);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取key对应的所有键值
     * @param key 键
     * @return 对应的多个<hashKey,value>
     */
    public Map<Object, Object> hmGet(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 批量设置值
     * @param key 键
     * @param map <hashKey, Object>组成的map
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean hmSet(String key, Map<String, Object> map){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 批量设置值并加过期时间
     * @param key 键
     * @param map <hashKey, Object>组成的map
     * @param timeout 过期时间(秒)
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean hmSet(String key, Map<String, Object> map, long timeout){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (timeout > 0){
                expire(key, timeout);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param hashKeys 哈希键,可以有多个 不能为null
     */
    public void hDelete(String key, Object... hashKeys){
        if (hashKeys != null && hashKeys.length > 0){
            redisTemplate.opsForHash().delete(key, hashKeys);
        }
    }

    /**
     * 判断哈希表中是否有该项的值
     * @param key 键 不能为null
     * @param hashKey hashKey 不能为null
     * @return <code>true:</code>存在,<code>false:</code>不存在
     */
    public boolean hHasKey(String key, String hashKey){
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    /**
     * hash递增,若不存在,就会创建一个,并把新增后的值返回
     * @param key 键
     * @param hashKey hashKey
     * @param delta 要增加几
     * @return 递增后的hashKey
     */
    public double hIncrement(String key, String hashKey, double delta){
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }
    /**
     * hash递增,若不存在,就会创建一个,并把新增后的值返回
     * @param key 键
     * @param hashKey hashKey
     * @param delta 要减少几
     * @return 递减后的hashKey
     */
    public double hDecrement(String key, String hashKey, double delta){
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    /*=============================Set start================================*/

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return Set中的所有值
     */
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将数据放入set缓存中
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values){
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将数据放入set缓存中
     * @param key 键
     * @param timeout 过期时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, long timeout, Object... values){
        try {
            long count = redisTemplate.opsForSet().add(key, values);
            if (timeout > 0){
                expire(key, timeout);
            }
            return count;
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return <code>true:</code>存在,<code>false:</code>不存在
     */
    public boolean sHasKey(String key, Object value){
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return 缓存的数据长度
     */
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值,可以为多个
     * @return 移除的个数
     */
    public long sDelete(String key, Object... values){
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /*=============================list start================================*/

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始下标
     * @param end 结束下标(若是-1,代表最后一个)
     * @return  list缓存的内容
     */
    public List<Object> lGet(String key, long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过索引获取list中的值
     * @param key 键
     * @param index 索引 index >= 0时,0表示头,1表示第二个元素;index < 0时,-1表示尾,-2表示倒数第二个元素
     * @return 值
     */
    public Object lGetByIndex(String key, long index){
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将数据放入list缓存中
     * @param key 键
     * @param value 值
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean lSet(String key, Object value){
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入list缓存中
     * @param key 键
     * @param value 值
     * @param timeout 过期时间
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean lSet(String key, Object value, long timeout){
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (timeout > 0){
                expire(key, timeout);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入list缓存中
     * @param key 键
     * @param value 值
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean lSet(String key, List<Object> value){
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入list缓存中
     * @param key 键
     * @param value 值
     * @param timeout 过期时间
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean lSet(String key, List<Object> value, long timeout){
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (timeout > 0){
                expire(key, timeout);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引下标
     * @param value 值
     * @return <code>true:</code>成功,<code>false:</code>失败
     */
    public boolean lUpdateByIndex(String key, long index, Object value){
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取list缓存长度
     * @param key 键
     * @return 缓存长度
     */
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除N个值为value的
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lDelete(String key, long count, Object value){
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
}

(四)在配置文件中注册RedisUtils

    <!--封装好的redis工具类-->
    <bean id="redisUtils" class="org.pc.util.RedisUtils">
        <property name="redisTemplate" ref="redisTemplate"/>
    </bean>

(五)使用样例

    @GetMapping(value = "/")
    public String initIndex(){
        //key:test value:test 有效期:10s
        if (redisUtils.set("test", "test", 10)){
            return "缓存成功!";
        }
        return "缓存失败!";
    }

  效果图:
这里写图片描述
  10s以后访问访问:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/panchang199266/article/details/80877244