程序员

Spring整合Redis存储数据

2018-09-10  本文已影响3人  程屁凹
the cat is named Java

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置JedisConnectionFactory

在resources目录下新建spring-redis.xml,在该文件中添加jedisConnectionFactory的bean定义:

<bean id="jedisConnectionFactory"      class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
      p:host-name="redis-server"
      p:port="redos-port" />

配置RedisTemplate

在spring-redis.xml文件中,添加redisTemplate的bean定义:

<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>
    <property name="hashKeySerializer">
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    </property>
    <property name="hashValueSerializer">
        <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
    </property>
    <!-- enable transaction  -->
    <property name="enableTransactionSupport" value="true"/>
</bean>

使用

自动装载redisTemplate依赖:

@Autowired 
val redisTemplate: RedisTemplate<String, String>

使用redisTemplate操作redis数据库:

class RedisHelper(val redisTemplate: RedisTemplate<String, String>) {

    */***
*     * add or update a key with value and expire*
*     */*
fun add(key: String, value: String, expire: Long? = null): Boolean = try {
        redisTemplate.opsForValue().set(key, value)
        if (expire is Long) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS)
        }
        true
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }

    */***
*     * get value of key*
*     */*
fun get(key: String): String {
        return redisTemplate.opsForValue().get(key) ?: ""
    }

    */***
*     * get expiration of key*
*     */*
fun ttl(key: String) = redisTemplate.getExpire(key)

    */***
*     * delete value by key*
*     */*
fun del(key: String): Boolean = try {
        redisTemplate.delete(key)
        true
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }

    */***
*     * check if the redis contains the key*
*     */*
fun has(key: String): Boolean = try {
        redisTemplate.hasKey(key)
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}
上一篇下一篇

猜你喜欢

热点阅读