美文网首页
SSM整合Redis

SSM整合Redis

作者: Jerry_Liang | 来源:发表于2019-04-16 11:42 被阅读0次

1.新建redis.properties

在classpath下创建redis.properties,内容如下:

redis.host=连接的redis服务器ip地址
redis.port=6379   //端口号
redis.password=   //你的redis密码
redis.dbIndex=0   //db索引,即使用哪个db
redis.maxIdle=50  
redis.maxTotal=100
redis.maxWaitMillis=3000
redis.testOnBorrow=true
redis.timeout=5000
redis.expiration=20 //设置关键字过期时间

2.新建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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/util
             http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:redis.properties"/>

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxTotal" value="${redis.maxTotal}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    <!-- 配置JedisConnectionFactory -->
    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}"/>
        <property name="database" value="${redis.dbIndex}" />
        <property name="poolConfig" ref="poolConfig" />
    </bean>
    <!-- 配置RedisTemplate -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>
    <!-- 配置RedisCacheManager -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate" />
        <property name="defaultExpiration" value="${redis.expiration}" />
    </bean>
    <!-- 配置RedisCacheConfig -->
    <bean id="redisCacheConfig" class="com.trace.app.framework.utils.RedisUtil">
        <constructor-arg ref="jedisConnectionFactory" />
        <constructor-arg ref="redisTemplate" />
        <constructor-arg ref="redisCacheManager" />
    </bean>
</beans>

并将该配置文件引入启动配置文件中,如我的是application_context.xml,因为该文件在web.xml做了如下引用

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/application_context.xml</param-value>
    </context-param>

所以我将spring-redis.xml引入application_context.xml中

<import resource="路径/spring-redis.xml"/>  //其中,路径可以是相对的也可以是绝对的

3.创建RedisUtil.class

/**
 * @Author: JerryLiang
 * @Date: 2019/4/16 10:00
 **/
@Component
public class RedisUtil {

    private volatile JedisConnectionFactory jedisConnectionFactory;
    private volatile RedisTemplate<String,String> redisTemplate;
    private volatile RedisCacheManager redisCacheManager;

    private static Logger logger = Logger.getLogger("RedisUtil");

    public RedisUtil() {
        super();
    }
    public RedisUtil(JedisConnectionFactory jedisConnectionFactory, RedisTemplate<String, String> redisTemplate,
                     RedisCacheManager redisCacheManager ) {
        this.jedisConnectionFactory = jedisConnectionFactory;
        this.redisTemplate = redisTemplate;
        this.redisCacheManager = redisCacheManager;
    }

    public JedisConnectionFactory getJedisConnecionFactory() {
        return jedisConnectionFactory;
    }

    public RedisTemplate<String, String> getRedisTemplate() {
        return redisTemplate;
    }


    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     */
    public boolean expire(String key, long time) {
     //   logger.info("set-expire-start");
        try{
            if(time > 0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
      //          logger.info("set-expire-success");
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

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

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

    /**
     *  删除缓存
     * @param key
     */
    @SuppressWarnings("unchecked")
    public boolean del(String key){
        if (key.equals("")|| key==null) {
            return false;
        }else{
            redisTemplate.delete(key);
            return true;
        }
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, String value, long time) {
      //  logger.info("set-session-key-start");
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
        //    logger.info("set-session-key-success");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

}

4.测试

将RedisUtil注入到我们需要使用的控制层中

@Autowired
private RedisUtil redisUtil;

调用

redisUtil.set("test","ssm")

查看结果


image.png

相关文章

  • SpringBoot整合Redis

    其实之前维护SSM项目的时候开发秒杀引入redis也有在网上翻天覆地的找整合的法子,Maven整合SSM和Redi...

  • ssm整合redis

    一、service 二、RedisCacheConfig 三、xml文件配置 maven的配置文件 ssm框架整合...

  • SSM整合Redis

    1.新建redis.properties 在classpath下创建redis.properties,内容如下: ...

  • SSM框架整合Redis做MyBatis二级缓存

    参考博文:3-SSM框架整合Redis做MyBatis二级缓存

  • ssm+redis 整合

    1:准备好 Redis 服务器,这里就不详细介绍了, 可以百度 windows 下如何安装 redis 服务器。 ...

  • SSM之整合Redis

    Redis安装与使用 第一步当然是安装Redis,这里以Windows上的安装为例。 首先下载Redis,可以选择...

  • 整合SSM

    SSM整合 整合思路 各自搭建SSM环境 使用Spring整合Mybatis 使用Spring整合SpringMV...

  • 12|第十二课:SSM整合

    一、SSM整合 SSM整合: Spring --- SpringMVC --- MyBatis (一)、Sprin...

  • mybatis整合redis缓存

    最近闲来无事开始学习缓存技术,首当其冲的就是接触到redis,多的不说,直接借着现有ssm框架整合redis进去,...

  • SpringMVC框架学习1:SSM 整合开发、SpringMV

    SSM 整合开发 SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行...

网友评论

      本文标题:SSM整合Redis

      本文链接:https://www.haomeiwen.com/subject/ezgvwqtx.html