使用redis缓存数据

该博客介绍了如何在项目中配置并使用Redis作为数据缓存。首先在配置文件中引入redisTemplate,并设置redis的相关属性。接着通过读取配置文件,定义接口和其实现类来操作Redis。在生成缓存Key时,采用了正则表达式进行动态替换,以实现个性化缓存键。
摘要由CSDN通过智能技术生成

首先在applicationContext.xml中引入redisTemplate

<bean id="propertyConfigurer" class="PropertiesUtils">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath*:*.properties</value>
            </list>
        </property>
    </bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.max_total}" />
        <property name="minIdle" value="${redis.min_idle}" />
        <property name="maxIdle" value="${redis.max_idle}" />
        <property name="maxWaitMillis" value="${redis.max_wait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        <property name="testOnReturn" value="${redis.testOnReturn}" />
        <property name="testWhileIdle" value="${redis.testWhileIdle}" />
    </bean>
<bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="jedisPoolConfig" />
        <property name="hostName" value="${redis.ip}" />
        <property name="port" value="${redis.port}" />
        <property name="database" value="${redis.db.index}" />
    </bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>

然后写一个redis.property去保存对应的配置
然后写一个读取配置的文件

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

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


public class PropertiesUtils  extends PropertyPlaceholderConfigurer {
    //所有属性文件的键值对
    private static Map<String, Object> ctxPropertiesMap;

    /**
     * 添加所有属性到map中
     * @see org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#processProperties(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.Properties)
     */
    @Override
    protected synchronized void processProperties(
            ConfigurableListableBeanFactory beanFactoryToProcess,
            Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        if (null==ctxPropertiesMap) {
        	ctxPropertiesMap = new HashMap<String, Object>();
        }
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            ctxPropertiesMap.put(keyStr, value);
        }
    }

    
    public static String getContextProperty(String name) {
        return null == ctxPropertiesMap || ctxPropertiesMap.get(name) == null ? "" : ctxPropertiesMap.get(name).toString();
    }


    public static String getContextProperty(String name, String defaultValue) {
        return null == ctxPropertiesMap || ctxPropertiesMap.get(name) == null ? defaultValue : ctxPropertiesMap.get(name).toString();
    }

    public static Integer getInt(String name) {
        String value = getContextProperty(name);
        if ((value + "").matches("-?\\d+")) {
            return Integer.parseInt(value);
        } else {
            return null;
        }
    }

    /**
     * @param name         属性名
     */
    public static Integer getInt(String name, Integer defaultValue) {
        String value = getContextProperty(name);
        if ((value + "").matches("-?\\d+")) {
            return Integer.parseInt(value);
        } else {
            return defaultValue;
        }
    }

}

首先定义一个接口

import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

public interface CacheService {


    /**
     * key
     *
     * @param key
     * @return 获取过期时间
     */
    public Long ttl(final String key);

    /**
     * 生成缓存 key
     *
     * @param namespace eg : carModle:{carFamily}:{id}:year
     * @param keys      eg:  audi,123
     * @return eg: carModle:audi:123:year
     */
    public String generateCacheKey(String namespace, Object... keys);


    public Boolean existsKey(String key);

    /**
     * 将对象添加到缓存中
     *
     * @param key   缓存的 key 值
     * @param value 对象
     */
    public void putIntoCache(final String key, final Object value);

    /**
     * 将对象添加到缓存中
     *
     * @param key   缓存的 key 值
     * @param value 对象
     * @param time  过期时间(多久之后过期) 单位为秒
     */
    public void putIntoCache(final String key, final Object value, final long time);

    /**
     * 清除缓存
     *
     * @param key 缓存的 key 值
     */
    public void clearCache(final String key);

    /**
     * 从缓存中获得对象
     *
     * @param key   缓存的 key
     * @param clazz 对象的类型
     * @return 缓存的 value
     */
    public <T> T getFromCache(final String key, final Class<T> clazz);

    /**
     * 从缓存中获取字符串
     * @param key
     * @return
     */
    String getStringFromCache(final String key);
    
    public <T> T getMapFromCache(final String key, final Class<T> clazz);
    public <T> T getObjectFromCache(final String key,final Class<T> clazz);
    /**
     * 根据 key ,从缓存中获取 list
     *
     * @param key   缓存的 key
     * @param clazz 对象的类型
     */
    public <T> List<T> getListFromCache(final String key, final Class<T> clazz);

    /**
     * 从缓存中批量获取 对象的值
     *
     * @param keys  缓存 key 的 list
     * @param clazz 对象的类型
     * @return
     */
    public <T> List<T> getListFromCache(final List<String> keys,
                                        final Class<T> clazz);

    /**
     * 自增 key
     *
     * @param key
     * @return 自增之后的 id
     */
    public Long incr(final String key);

    /**
     * 自增 key
     *
     * @param key
     * @return 自增之后的 id
     */
    public Long incr(final String key, final Long expireTime);

    /**
     * hashSet put操作
     *
     * @param hashName   hash hash表的名字
     * @param filedName  key 值
     * @param value      key 对应的 value值
     * @param expireTime 超时时间
     * @return
     */
    Boolean hset(String hashName, String filedName, Object value,
                 long expireTime);

    /**
     * hashSet 操作
     *
     * @param hashName  hash hash表的名字
     * @param filedName key 值
     * @param value     key 对应的value值
     * @return
     */
    Boolean hset(String hashName, String filedName, Object value);

    /**
     * hashGet hash get 操作
     *
     * @param hashName  hash 表的名字
     * @param filedName key 值
     * @return 对应的 value 的值
     */
    Object hget(String hashName, String filedName);

    /**
     * hashGet hash getAll 操作
     *
     * @param hashName  hash 表的名
     * @param filedName key 值
     * @return 对应的 value 的值
     */
    <T> List<T> hgetall(String hashName, final Class<T> clazz);

    /**
     * hashGet hash haskey 操作
使用Redis缓存数据可以提高应用程序的性能和响应速度。下面是使用Redis缓存数据的步骤: 1. 安装Redis:首先,您需要在您的系统上安装Redis。您可以从Redis官方网站下载并按照安装说明进行安装。 2. 连接到Redis使用Redis客户端连接到Redis服务器。您可以使用命令行工具或编程语言提供的Redis客户端库来连接到Redis。 3. 设置缓存数据使用Redis的SET命令将数据存储在缓存中。例如,以下命令将名为"username"的键与值"john"关联起来: ``` SET username john ``` 4. 获取缓存数据使用Redis的GET命令从缓存中获取数据。例如,以下命令将返回名为"username"的键的值: ``` GET username ``` 5. 设置过期时间:您可以使用Redis的EXPIRE命令为缓存数据设置过期时间。例如,以下命令将名为"username"的键设置为在60秒后过期: ``` EXPIRE username 60 ``` 6. 删除缓存数据使用Redis的DEL命令从缓存中删除数据。例如,以下命令将删除名为"username"的键: ``` DEL username ``` 7. 使用缓存数据:在应用程序中,您可以首先检查缓存中是否存在所需的数据。如果存在,则直接从缓存中获取数据,而不必访问数据库。如果缓存中不存在所需的数据,则从数据库中获取数据,并将其存储在缓存中以供将来使用。 请注意,以上步骤仅为使用Redis缓存数据的基本示例。实际应用中,您可能需要更复杂的逻辑来处理缓存数据的更新和失效等情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值