Spring中使用RedisTemplate

项目目录结构

maven中引入Redis相关依赖

<!-- redis客户端jar -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.3</version>
    </dependency>

    <!-- spring-redis实现 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.7.2.RELEASE</version>
    </dependency>

redis.properties 配置redis 连接信息

redis.host=127.0.0.1
redis.port=6379
#redis.pass=123456
  
  
redis.maxIdle=300
redis.maxWaitMillis=1000
redis.testOnBorrow=true
# 应用于2这个库 可以自行选择
redis.database=2
redis.timeout=0
redis.usePool=true
redis.enableTransactionSupport=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" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        ">

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"
          p:maxIdle="${redis.maxIdle}" p:maxWaitMillis="${redis.maxWaitMillis}" p:testOnBorrow="${redis.testOnBorrow}">
    </bean>

    <bean id="jdkSerializationRedisSerializer"
          class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>

    <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}"  p:poolConfig-ref="poolConfig"
          p:usePool="${redis.usePool}"
          p:database="${redis.database}"
          p:timeout="${redis.timeout}"/>


    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:defaultSerializer-ref="jdkSerializationRedisSerializer"
          p:keySerializer-ref="jdkSerializationRedisSerializer"
          p:valueSerializer-ref="jdkSerializationRedisSerializer"
          p:connectionFactory-ref="jedisConnFactory"
          p:enableTransactionSupport="${redis.enableTransactionSupport}"
    >
    </bean>

</beans>

applicationContext.xml配置

读取redis.properties文件

引入spring-redis.xml配置文件

<!-- 加载读取property配置文件 ,PropertyPlaceholderConfigurer(容器后处理器)支持从properties文件中读入配置并注入到bean中 -->
    <bean
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <!-- 可从jvm虚拟机的参数中获得配置信息 -->
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:redis/redis.properties</value>
            </list>
        </property>
    </bean>

 <import resource="../redis/spring-redis.xml"/>

RedisUtil工具类 我只写了部分方法

package cn.liziy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtil
 * @Author:Liziy
 * @Date 2020/5/30 20:19
 * @Description:
 **/
@Component
public class RedisUtil {
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * @Author liziyang
     * @Description 获取缓存
     * @Date 20:21 2020/5/30
     * @Param [key] 键
     * @return java.lang.Object 值
     **/
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    /**
     * @Author liziyang
     * @Description 设置缓存
     * @Date 20:22 2020/5/30
     * @Param [key, value]
     * @return boolean false 失败 / true 成功
     **/
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * @Author liziyang
     * @Description 添加缓存并设置过期时间
     * @Date 13:33 2020/5/31
     * @Param   [key, 键
     *          value, 值
     *          time 时间(秒) time要大于0 如果time小于等于0 将设置无限期]
     * @return boolean true成功 false 失败
     **/
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

controller

 @GetMapping("/setredis")
    public @ResponseBody
    ApiResponse  setredis(String key,String value){
        Object o = redisUtil.set(key,value);
        return ApiResponse.ofSuccess(o);

    }

@GetMapping("/getredis")
    public @ResponseBody
    Object getredis(String key){
        Object o = redisUtil.get(key);
        return o;

    }

   

 

posted @ 2020-06-01 14:21  火星的巧克力  阅读(2545)  评论(0编辑  收藏  举报
/* 返回顶部代码 */ TOP