Redis的基本使用

Posted 浪味仙人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis的基本使用相关的知识,希望对你有一定的参考价值。

redis.properties

redis.ip=redis.test.yiyaowang.com
redis.port=6379
redis.timeout=8000
redis.maxTotal=100
redis.maxIdle=200
redis.maxWaitMillis=8000
redis.testOnBorrow=true

spring-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dbkeypropertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!--密钥存放位置,由运维告知-->
                <value>file:/etc/dbprivatekey.properties</value>
                <value>classpath*:config/*.properties</value>
            </list>
        </property>
    </bean>
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="testOnBorrow" value="true"/>
        <property name="maxIdle" value="200"/>
        <property name="maxWaitMillis" value="8000"/>
    </bean>
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
        <constructor-arg index="0">
            <ref bean="jedisPoolConfig"/>
        </constructor-arg>
        <constructor-arg index="1" value="${redis.ip}" type="String"/>
        <constructor-arg index="2" value="${redis.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
        <constructor-arg index="4" value="${redis.common.key}" type="String"/>  <!--redis.common.key 定义在 /etc/dbprivatekey.properties 中 -->
    </bean>
</beans>
JedisUtil.java
package com.yyw.scs.util;

import com.yyw.scs.framework.kit.CustomizedPropertyConfigurer;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.LinkedHashSet;
import java.util.Set;

@Service
public class JedisUtil {

    private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);


    public static String DEFAULT_PREF = "scs_delay_rate_";
    /**
     * 默认过期时间10分钟
     */
    public static int DEFAULT_EXP_TIME = 10 * 60;

    public static String DATE_TIME = "初始化";

    private JedisPool jedisPool;

    /**
     * 释放jedis资源
     *
     * @param jedis
     */
    public void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool != null) {
            jedisPool.returnResource(jedis);
        }
    }

    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Get key erroe :" + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
            return null;
        } finally {
            returnResource(jedis);
        }
    }

    public byte[] bget(String key){
        Jedis jedis = null;
        try {
            jedis=getJedis();
            return jedis.get(key.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Get key erroe :"+e);
            if(jedisPool != null && jedis != null){
                jedisPool.returnBrokenResource(jedis);
            }
            return null;
        }finally{
            returnResource(jedis);
        }
    }

    public String getStr(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Get key erroe :" + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
            return null;
        } finally {
            returnResource(jedis);
        }
    }

    public void set(String key, String value, int seconds) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(key, value);
            jedis.expire(key, seconds);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Set keyex error : " + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            returnResource(jedis);
        }
    }

    public void bset(String key, byte[]  value, int seconds){
        Jedis jedis = null;
        try {
            jedis=getJedis();
            jedis.set(key.getBytes(), value);
            jedis.expire(key.getBytes(), seconds);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Set keyex error : "+e);
            if(jedisPool != null && jedis != null){
                jedisPool.returnBrokenResource(jedis);
            }
        } finally{
            returnResource(jedis);
        }
    }

    public void del(String key) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Del key error : " + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            returnResource(jedis);
        }
    }

    public void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Set key error : " + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            returnResource(jedis);
        }
    }

    //获取所有的keys
    public Set<String> keys(final String pattern) {
        Set<String> keys = new LinkedHashSet<String>();
        Jedis jedis = null;
        try {
            jedis = getJedis();
            keys = jedis.keys(pattern);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Set key error : " + e);
            if (jedisPool != null && jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            if (jedisPool != null && jedis != null) {
                jedisPool.returnResource(jedis);
            }
        }
        return keys;
    }

    /**
     * 同步获取Jedis实例
     *
     * @return Jedis
     */
    public synchronized Jedis getJedis() {
        if (jedisPool == null) {
            jedisPool = getJedisPool();
        }
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Get jedis error : " + e);
        }
        return jedis;
    }

    public JedisPool getJedisPool() {
        if (jedisPool == null) {
            try {
                String ip = CustomizedPropertyConfigurer.getProperty("redis.ip");
                String port = CustomizedPropertyConfigurer.getProperty("redis.port");
                String timeout = CustomizedPropertyConfigurer.getProperty("redis.timeout");
                String maxTotal = CustomizedPropertyConfigurer.getProperty("redis.maxTotal");
                String maxIdle = CustomizedPropertyConfigurer.getProperty("redis.maxIdle");
                String maxWaitMillis = CustomizedPropertyConfigurer.getProperty("redis.maxWaitMillis");
                String testOnBorrow = CustomizedPropertyConfigurer.getProperty("redis.testOnBorrow");
                String key = CustomizedPropertyConfigurer.getProperty("redis.common.key");

                JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                jedisPoolConfig.setMaxTotal(Integer.valueOf(maxTotal));
                jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
                jedisPoolConfig.setMaxWaitMillis(Long.valueOf(maxWaitMillis));
                jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(testOnBorrow));
                if (StringUtils.isNotEmpty(key))
                    jedisPool = new JedisPool(jedisPoolConfig, ip, Integer.valueOf(port), Integer.valueOf(timeout), key);
                else {
                    jedisPool = new JedisPool(jedisPoolConfig, ip, Integer.valueOf(port), Integer.valueOf(timeout));
                }
            } catch (Exception e) {
                logger.error("JedisUtil init Error", e);
            }
        }
        return jedisPool;
    }

    public  String generateRedisKey(MethodSignature signature, Object[] args){
        StringBuilder keyBuilder =new StringBuilder(DEFAULT_PREF);
        String methodName =signature.getName();
        keyBuilder.append(methodName);
        if(args!=null && args.length>0){
            int i=0;
            for(Object arg:args){
                keyBuilder.append("_arg").append(i++).append("_").append(String.valueOf(arg));
            }
        }
        return keyBuilder.toString();
    }
}
DelayRateServiceAspect.java
package com.yyw.scs.wms.service.impl;

import com.alibaba.fastjson.JSON;
import com.yyw.scs.util.DateUtils;
import com.yyw.scs.util.JedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Date;

@Aspect
@Component
public class DelayRateServiceAspect implements Ordered {

    @Autowired
    private JedisUtil jedisUtil;

    private static Logger LOGGER = LoggerFactory.getLogger(DelayRateServiceAspect.class);

    @Around("execution(* com.yyw.scs.wms.service.impl.DelayRateServiceImpl.find*(..))")
    public Object timeAround(ProceedingJoinPoint joinPoint) {
        // 定义返回对象、得到方法需要的参数
        Object obj = null;
        try {
            Object[] args = joinPoint.getArgs();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            String redisKey = generateRedisKey(methodSignature, args);
            byte[] res = jedisUtil.bget(redisKey);
            if (res != null) {
                obj = objectDeserialization(res);
            } else {
                obj = joinPoint.proceed(args);
                if (obj != null) {
                    jedisUtil.bset(redisKey, objectSerialiable(obj), JedisUtil.DEFAULT_EXP_TIME);
                    JedisUtil.DATE_TIME = DateUtils.dateFormatToDatestr(new Date(), "MM-dd HH:mm");
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            LOGGER.error("DelayRateServiceAspect 报错", throwable);
        }
        return obj;
    }

    //字符串反序列化为对象
    public Object objectDeserialization(byte[] value) {
        Object newObj = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(value);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            newObj = objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("IOException ", e);
        } catch (ClassNotFoundException e) {
            LOGGER.warn("ClassNotFoundException ", e);
        } catch (IOException e) {
            LOGGER.warn("IOException ", e);
        }
        return newObj;
    }

    //对象序列化为字符串
    public byte[] objectSerialiable(Object obj) {
        Byte[] serStr = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            byte[] byteArray = byteArrayOutputStream.toByteArray();

            objectOutputStream.close();
            byteArrayOutputStream.close();
            return byteArray;
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("UnsupportedEncodingException data:" + JSON.toJSONString(obj), e);
        } catch (IOException e) {
            LOGGER.warn("IOException data:" + JSON.toJSONString(obj), e);
        }
        System.out.println(serStr);
        return null;
    }

    public String generateRedisKey(MethodSignature signature, Object[] args) {
        StringBuilder keyBuilder = new StringBuilder(JedisUtil.DEFAULT_PREF);
        String methodName = signature.getName();
        keyBuilder.append(methodName);
        if (args != null && args.length > 0) {
            int i = 0;
            for (Object arg : args) {
                keyBuilder.append("_arg").append(i++).append("_").append(String.valueOf(arg));
            }
        }
        return keyBuilder.toString();
    }

    @Override
    public int getOrder() {
        return 1;
    }

}

 

以上是关于Redis的基本使用的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp Robolution基本代码片段

如何从片段外部清除/重置地图?

JavaScript 代码片段

如何利用redis来进行分布式集群系统的限流设计

jedis连接redis

Android 使用两个不同的代码片段获取当前位置 NULL