ssm整合redis

目录

1.pom.xml

2.配置文件

项目结构:

         整合redis的配置:

redis.properties

注意:

3.redis工具类

applicationContext.xml

 AssertUtil

RedisClient

domain

3.测试


续上一篇文章的基础进行写代码

1.pom.xml

导入redis和连接池jedis的依赖

关于后面代码的编写【包括配置和测试】,这两个依赖的版本【过高或过低】可能会导致报错,可自行百度修改。

 <!--整合redis-->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.5.0.RELEASE</version>
    </dependency>
    <!--redis的连接池jedis-->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>

2.配置文件

项目结构:

        

 我的配置全写在一个xml里的【包括整合mybatis和springmvc的配置等等】

         整合redis的配置:

    <!--ignore-unresolvable="true" ignore-resource-not-found="true"
    因为上面也使用了 <context:property-placeholder location
      使用情况之一: 避免发生 重复扫描所有bean而导致的解析失败现象 建议搭配使用
       -->
    <!--扫面redis配置文件-->
    <context:property-placeholder location="classpath:redis.properties"
                                  ignore-unresolvable="true" ignore-resource-not-found="true"
                                  system-properties-mode="NEVER"></context:property-placeholder>

    <!--jedis连接池配置-->
    <bean class="redis.clients.jedis.JedisPoolConfig" id="jedisPoolConfig">
        <!--最大空闲连接数 负数表示无限制-->
        <property name="maxIdle" value="${redis.pool.maxIdle}"></property>
        <!--最小空闲连接数 -->
        <property name="minIdle" value="${redis.pool.minIdle}"></property>
        <!--最大连接数 负数表示无限制-->
        <property name="maxTotal" value="${redis.pool.maxTotal}"></property>
        <!--最大阻塞时间-->
        <property name="maxWaitMillis" value="${redis.pool.maxWait}"></property>
        <!--使用连接时,测试是否连接成功-->
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"></property>
    </bean>
    
    <!--redis连接工厂配置-->
    <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" id="jedisConnectionFactory">
        <!--redis的ip-->
        <property name="hostName" value="${redis.host}"></property>
        <!--端口-->
        <property name="port" value="${redis.port}"></property>
        <!--密码-->
        <property name="password" value="${redis.passWord}"></property>
        <!--数据库索引,库号-->
        <property name="database" value="${redis.database}"></property>
        <!--连接超时时间-->
        <property name="timeout" value="${redis.timeout}"></property>
        <!--jedis连接池配置-->
        <property name="poolConfig" ref="jedisPoolConfig"></property>
    </bean>

    <!--redis操作模板 面向对象-->
    <bean class="org.springframework.data.redis.core.StringRedisTemplate" id="redisTemplate">
        <!--加载连接工厂-->
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
        <!--对象序列化-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="valueSerializer" >
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer">
            </bean>
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
        </property>
        <property name="hashValueSerializer" >
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
        </property>

        <!--开启事务支持-->
        <property name="enableTransactionSupport" value="true"></property>
    </bean>

redis.properties

redis.pool.maxIdle=20
redis.pool.minIdle=0
redis.pool.maxTotal=100
redis.pool.maxWait=-1
redis.pool.testOnBorrow=true

redis.database=1
redis.timeout=3000
redis.host=127.0.0.1
redis.port=6379
redis.passWord=123456

注意:

① ignore-unresolvable="true" ignore-resource-not-found="true" 的用法,建议自行百度了解,基于这个项目已经扫描了jdbc.properties,保险起见,我选择两个都加上并设置为true,加了也没什么坏事。

②依赖版本问题导致redis连接池和连接工厂的配置<property name 中有些参数名字不一致,或已被淘汰,根据实际情况自行修改版本及参数名

③redis操作模板中的序列化

        存入redis的实体类对象记得要实现 Serializable 接口,否则会报错

        配置文件中,在hashValueSerializer和ValueSerializer的bean属性中,除了

JdkSerializationRedisSerializer还有其他的选择,自行百度了解。

④别忘了在redis操作模板中把事务支持开启     

3.redis工具类

可有可无,我是为了方便调用并复习@component注解,还加入了断言工具类

applicationContext.xml

扫描utils包

 <!--包扫描-->
    <context:component-scan base-package="cn.lyd.controller,cn.lyd.service,cn.lyd.utils,cn.lyd.vo"></context:component-scan>

 AssertUtil

package cn.lyd.utils.asserts;

import org.springframework.stereotype.Component;

@Component
public class AssertUtil {

    /**
     * 判断字符串是否为空
     * @param key
     * @return
     */
    public boolean StringIsNull(String key){
        if (key==null && key.equalsIgnoreCase("")){
            return true;
        }else {
            return false;
        }
    }


    /**
     * 判断字符串不为空
     * @param key
     * @return
     */
    public boolean StringNotNull(String key){
        boolean b = this.StringIsNull(key);
        return b==true?false:true;
    }






}

RedisClient

package cn.lyd.utils.redis;

import cn.lyd.utils.asserts.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@Component
public class RedisClient {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AssertUtil assertUtil;


    /**
     * 存放普通键值对 并设置缓存时间
     * @param key 键
     * @param value 值
     * @param time 存放时间
     * @return
     */
    public boolean set(String key , Object value , long time) {
        try {

            if (time>0) {
                this.redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(key,value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            System.out.println("测试完毕");
        }

    }


    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        try {
            if (assertUtil.StringNotNull(key)) {
                Boolean aBoolean = redisTemplate.hasKey(key);
                return aBoolean;
            }else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 根据key获取value
     * @param key
     * @return
     */
    public Object get(String key) {
        try {
            if (assertUtil.StringNotNull(key)) {
                Object o = redisTemplate.opsForValue().get(key);
                return o;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            System.out.println("测试完毕");
        }

    }


    /**
     * 获取剩余时间
     * @param key
     * @return
     */
    public Long getExpire(String key){
        try {
            if (assertUtil.StringNotNull(key)&&this.hasKey(key)) {
                Long expire = redisTemplate.getExpire(key);
                return expire;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }





}

domain

别忘了实现Serializable接口,才能序列化

public class Emp implements Serializable

3.测试

import cn.lyd.domain.Emp;
import cn.lyd.utils.redis.RedisClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {

    @Autowired
    private RedisClient redisClient;

    @Test
    public void test1() throws Exception{
        Emp emp = new Emp();
        emp.setEname("ss");
        emp.setEage(23);
        emp.setEphone("12312323");
        redisClient.set("缓存1",emp,10);
    }

    @Test
    public void test2() throws Exception{
        Object o = redisClient.get("缓存1");
        System.out.println(o);
    }
    @Test
    public void test3() throws Exception{
        Long redisClientExpire = redisClient.getExpire("缓存1");
        System.out.println(redisClientExpire);
    }


}

个人学习总结,便于将来复习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值