Redis总结(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hellogbaby/article/details/80352375

初识Redis

使用Spring+SpringMVC+Mybatis框架 整合Redis

  • 安装redis,安装redis可视化工具
  • Spring整合Redis
  • Redis在项目中的使用

安装Redis

1、下载Redis压缩包,解压到本地目录,下载目录链接: https://pan.baidu.com/s/1qRdSWDjOvRH1Cm2kM5bbNQ 密码: s271
2、解压成功之后,使用管理员权限打开CMD,跳转到redis解压目录,例如:cd C:\redis,然后执行命令 redis-server.exe redis.windows.conf 开启Redis,(这个CMD窗口不能关闭,相当于redis服务器开启)
3、修改redis基本配置。配置连接密码:在redis目录中找到redis.windows.conf配置文件,打开,添加一行:requirepass 123456,密码123456配置完成
4、redis安装完毕。

安装Redis可视化工具

1、下载地址链接: https://pan.baidu.com/s/1KHgYCwMpG14QeV3AVMCMGQ 密码: 2kjr,下载之后直接安装即可。

Redis和Spring的简单整合

1、在Spring配置文件中添加Redis的配置标签

<!-- 配置JedisPoolConfig实例 -->
<bean id="poolConfig"   class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="300" />
    <property name="maxTotal" value="600" />
    <property name="maxWaitMillis" value="1000" />
    <property name="testOnBorrow" value="true" />
</bean>

<!-- 配置JedisConnectionFactory-->
<bean id="jedisConnectionFactory"
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="127.0.0.1" />
    <property name="port" value="6379" />
    <property name="password" value="123456" />
    <property name="database" value="0" />
    <property name="timeout" value="100000" />
    <property name="poolConfig" ref="poolConfig" />
</bean>

<!-- 配置RedisTemplate -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >  
     <property name="connectionFactory" ref="jedisConnectionFactory" />  
     <property name="keySerializer" >  
         <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
     </property>  
     <property name="valueSerializer" >  
         <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
     </property>  
 </bean>


 <!-- cache配置 -->  
 <bean id="methodCacheInterceptor" class="com.aite.utils.MethodCacheInterceptor" >  
     <property name="redisUtil" ref="redisUtil" />  
   </bean > 
   <bean id="redisUtil" class="com.xxx.utils.RedisUtil" >  
     <property name="redisTemplate" ref="redisTemplate" />  
   </bean > 

   <!-- 需要加入缓存的类或方法 -->  
 <bean id="methodCachePointCut"  class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" >  
  <property name="advice" ref="methodCacheInterceptor"/>  
  <property name="patterns" >  
      <list>  
       <!-- 确定正则表达式列表 -->  
         <value>com\.xxx\.service\.redis\...*Service</value >  

      </list>  
  </property>  
</bean > 

2、创建java-util类 : methodCacheInterceptor 和 RedisUtil

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

public class RedisUtil {
    private Logger logger = Logger.getLogger(RedisUtil.class);  
    private RedisTemplate<Serializable, Object> 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 Object get(final String key) {  
        Object result = null;  
        ValueOperations<Serializable, Object> operations = redisTemplate  
                .opsForValue();  
        result = operations.get(key);  
        return result;  
    }  

    /** 
     * 写入缓存 
     *  
     * @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 void setRedisTemplate(  
            RedisTemplate<Serializable, Object> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
}  




import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

public class MethodCacheInterceptor implements MethodInterceptor {  
    private Logger logger = Logger.getLogger(MethodCacheInterceptor.class);  
    private RedisUtil redisUtil;  
    private List<String> targetNamesList; // 不加入缓存的service名称  
    private List<String> methodNamesList; // 不加入缓存的方法名称  
    private Long defaultCacheExpireTime = (long)3600; // 缓存默认的过期时间  
    private Long xxxRecordManagerTime; //  
    private Long xxxSetRecordManagerTime; //  

    /** 
     * 初始化读取不需要加入缓存的类名和方法名称 
     */  
    public MethodCacheInterceptor() {  
        try {  
             File f = new File("D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties");   
             //配置文件位置直接被写死,有需要自己修改下  
             InputStream in = new FileInputStream(f);   
//          InputStream ins = getClass().getClassLoader().getResourceAsStream(  
//                  "D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties");  
            Properties p = new Properties();  
            p.load(in);  
            // 分割字符串  
            String[] targetNames = p.getProperty("targetNames").split(",");  
            String[] methodNames = p.getProperty("methodNames").split(",");  

            // 加载过期时间设置  
            defaultCacheExpireTime = Long.valueOf(p.getProperty("defaultCacheExpireTime"));  
            xxxRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxRecordManager"));  
            xxxSetRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxSetRecordManager"));  
            // 创建list  
            targetNamesList = new ArrayList<String>(targetNames.length);  
            methodNamesList = new ArrayList<String>(methodNames.length);  
            Integer maxLen = targetNames.length > methodNames.length ? targetNames.length  
                    : methodNames.length;  
            // 将不需要缓存的类名和方法名添加到list中  
            for (int i = 0; i < maxLen; i++) {  
                if (i < targetNames.length) {  
                    targetNamesList.add(targetNames[i]);  
                }  
                if (i < methodNames.length) {  
                    methodNamesList.add(methodNames[i]);  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    public Object invoke(MethodInvocation invocation) throws Throwable {  
        Object value = null;  

        String targetName = invocation.getThis().getClass().getName();  
        String methodName = invocation.getMethod().getName();  
        // 不需要缓存的内容  
        //if (!isAddCache(StringUtil.subStrForLastDot(targetName), methodName)) {  
        if (!isAddCache(targetName, methodName)) {  
            // 执行方法返回结果  
            return invocation.proceed();  
        }  
        Object[] arguments = invocation.getArguments();  
        String key = getCacheKey(targetName, methodName, arguments);  
        System.out.println(key);  

        try {  
            // 判断是否有缓存  
            if (redisUtil.exists(key)) {  
                return redisUtil.get(key);  
            }  
            // 写入缓存  
            value = invocation.proceed();  
            if (value != null) {  
                final String tkey = key;  
                final Object tvalue = value;  
                new Thread(new Runnable() {  
                    public void run() {  
                        if (tkey.startsWith("com.service.impl.xxxRecordManager")) {  
                            redisUtil.set(tkey, tvalue, xxxRecordManagerTime);  
                        } else if (tkey.startsWith("com.service.impl.xxxSetRecordManager")) {  
                            redisUtil.set(tkey, tvalue, xxxSetRecordManagerTime);  
                        } else {  
                            redisUtil.set(tkey, tvalue, defaultCacheExpireTime);  
                        }  
                    }  
                }).start();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            if (value == null) {  
                return invocation.proceed();  
            }  
        }  
        return value;  
    }  

    /** 
     * 是否加入缓存 
     *  
     * @return 
     */  
    private boolean isAddCache(String targetName, String methodName) {  
        boolean flag = true;  
        if (targetNamesList.contains(targetName)  
                || methodNamesList.contains(methodName)) {  
            flag = false;  
        }  
        return flag;  
    }  

    /** 
     * 创建缓存key 
     * 
     * @param targetName 
     * @param methodName 
     * @param arguments 
     */  
    private String getCacheKey(String targetName, String methodName,  
            Object[] arguments) {  
        StringBuffer sbu = new StringBuffer();  
        sbu.append(targetName).append("_").append(methodName);  
        if ((arguments != null) && (arguments.length != 0)) {  
            for (int i = 0; i < arguments.length; i++) {  
                sbu.append("_").append(arguments[i]);  
            }  
        }  
        return sbu.toString();  
    }  

    public void setRedisUtil(RedisUtil redisUtil) {  
        this.redisUtil = redisUtil;  
    }  
}  

3、简单Spring+Redis整合完成

Redis在项目中的使用

Redis数据放在内存中,访问速度快,一般在项目中和数据库配合使用。数据库存书数据,redis用于缓存。
可以把从数据库搜索出的数据集放在Redis中,使用这些数据的时候直接先取Redis数据,若redis中没有数据,再去查询数据库。可以增加项目运行效率。

`

阅读更多

没有更多推荐了,返回首页