分享

Spring中spring-data-redis的使用

丫丫 发表于 2017-1-9 11:48:55 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 2 12624
本帖最后由 pig2 于 2017-1-10 09:04 编辑
问题导航

1、什么是spring-data-redis?
2、spring-data-redis依赖哪些jar?
3、如何使用spring-data-redis?








Redis是一种特殊的类型的数据库,它被称为一种key-value存储。key-value存储保存的是键值对。实际上,key-value存储于哈希Map有很大的相似。
spring data是一种面向模板的数据访问,能够在使用Redis的时候,为我们提供了帮助。于是就有了spring-data-redis。

1. spring-data-redis的简介





spring-data-redis包含了多个模板实现,用来完成Redis数据库的存取功能。创建spring-data-redis模板之前,我们首先需要一个Redis连接工厂,spring-data-redis提供了四个连接工厂供我们选择。

2.spring-data-redis所需要依赖



[mw_shl_code=xml,true]      <dependency>            
<groupId>redis.clients</groupId>            
<artifactId>jedis</artifactId>            
<version>2.8.0</version>        
</dependency>        
<dependency>            
<groupId>org.springframework.data</groupId>            
<artifactId>spring-data-redis</artifactId>           
<version>1.6.2.RELEASE</version>        
</dependency>[/mw_shl_code]
      

3. spring-data-redis的使用


3.1 连接到Redis

Redis连接工厂会生成到Redis数据库服务器的连接。spring-data-redis为四种Redis客户端实现了连接工厂:



  • JedisConnectionFactory
  • JredisConnectionFactory
  • LettuceConnectionFactory
  • SrpConnectionFactory
    具体选择哪一种取决于自己。

(1)创建redis.properties:

[mw_shl_code=text,true]
maxTotal=8
#最大空闲时间
maxIdle=8
#最短空闲时间
minIdle=0
#最大的等待时间
maxWaitMillis=6000
#Redis的连接地址
hostR=127.0.0.1
#端口
portR=6379[/mw_shl_code]

(2)创建spring-redis.xml


[mw_shl_code=xml,true]<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/s ... ing-context-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/s ... ring-rabbit-1.2.xsd">

    <!-- 引入redis.properties配置文件-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:redis.properties" /> </bean>

    <!-- redis连接池的配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${maxTotal}" />
        <property name="maxIdle" value="${maxIdle}" />
        <property name="minIdle" value="${minIdle}" />
        <property name="maxWaitMillis" value="10000" />
        <property name="minEvictableIdleTimeMillis" value="300000"></property>
        <property name="numTestsPerEvictionRun" value="3"></property>
        <property name="timeBetweenEvictionRunsMillis" value="60000"></property>
   </bean>
    <!-- 工厂类配置 -->
    <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${hostR}" />
        <property name="port" value="${portR}" />
        <property name="poolConfig" ref="jedisPoolConfig" />
         <property name="timeout" value="15000"></property>
        <property name="usePool" value="true"></property>
    </bean>

    <!-- redisTemplate配置 -->
    <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="enableTransactionSupport" value="true" />
    </bean>

</beans>[/mw_shl_code]

以上是我配置的jedisPoolConfig,jedisConnectionFactory,redisTemplate。


3.2 使用RedisTemplate


Redis连接工厂会生成到Redis key-value存储的连接(以RedisConnection的形式。)借助RedisConnection,可以存储和读取数据。

spring-redis-data以模板的形式提供了较好等级的数据访问方案。实际上,spring-data-redis提供了两个模板:

  • RedisTemplate
  • StringRedisTemplate

其中RedisTemplate使用两个类型进行了参数。第一个参数是key的类型,第二个参数是value的类型,而StringRedisTemplate是RedisTemplate的扩展,只关注String类型,也就是key和vlaue都是String类型。


3.2.1 RedisTemplate使用简单值


假设我们想通过RedisTemplate

[mw_shl_code=java,true] public class UserRedisDaoImp extends AbstractBaseRedisTemplete<User>
              implements IUserRedisDao {

    @Override
    public User findById(String key) {
        return (User) redisTemplate.opsForValue().get(key);
    }

    @Override
    public void saveUser(String key,User user) {
         redisTemplate.opsForValue().set(key, user);
    }

}[/mw_shl_code]

3.2.2 RedisTemplate使用List值

使用List类型的value与之类似,只需要使用opForList()方法,

[mw_shl_code=java,true]
package com.lidong.core.user.dao;
import java.util.List;
import com.lidong.model.user.User;
import com.lidong.util.AbstractBaseRedisTemplete;

public class UserRedisDaoImp extends AbstractBaseRedisTemplete<User>
              implements IUserRedisDao {
    @Override    public List<User> getUserList(String key,long start,long end) {
        return  redisTemplate.opsForList().range(key, 0, end);
    }
    @Override    public Long addUserToUserList(String key, User user) {
        return redisTemplate.opsForList().leftPush(key, user);
    }
}
[/mw_shl_code]

3.2.3 RedisTemplate使用Set值

除了使用List类型和value类型,我们还可以使用opForSet()的方法操作Set,最为常用的的就是向Set中添加一个元素:


[mw_shl_code=java,true]
package com.lidong.core.user.dao;
import java.util.List;
import com.lidong.model.user.User;
import com.lidong.util.AbstractBaseRedisTemplete;

public class UserRedisDaoImp extends AbstractBaseRedisTemplete<User>               
                                            implements IUserRedisDao {   

       @Override    public List<User> getUserList(String key,long start,long end) {
        return  redisTemplate.opsForList().range(key, 0, end);   
       }   

      @Override    public Long addUserToUserList(String key, User user) {
        return redisTemplate.opsForList().leftPush(key, user);
    }
}[/mw_shl_code]


3.2.3 RedisTemplate使用Set值



除了使用List类型和value类型,我们还可以使用opForSet()的方法操作Set,最为常用的的就是向Set中添加一个元素:

[mw_shl_code=java,true]@Override
    public void saveUser(String key,User user) {
         redisTemplate.opsForSet().add(key, user);
    }[/mw_shl_code]

在我们有多个Set,并对这些Set集合进行差、交、并的操作。

[mw_shl_code=java,true]Set<User> difference = redisTemplate.opsForSet().difference("users1", "users2");
          Set<User> union = redisTemplate.opsForSet().union("users1", "users2");
          Set<User> intersect = redisTemplate.opsForSet().intersect("users1", "users2");
          //我还可以移除Set中的元素
          Long remove = redisTemplate.opsForSet().remove("user1", user);
[/mw_shl_code]


3.2.4 RedisTemplete绑定到某个key上


我们可以将Value、List、Set等可以绑定到指定的key上。这些用个的不太多,但是也简单。这里就不具体写了。


3.2.5 构造AbstractBaseRedisTemplete


[mw_shl_code=java,true]package com.lidong.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
/**
* 基础的RedisTemplete
* @author lidong
* @param <T>
* @date 2017-1-5
*/
public abstract class AbstractBaseRedisTemplete<T> implements
        ApplicationContextAware {


    protected RedisTemplate<String,T>  redisTemplate;

     /**
     * @Description RedisTemplate
     * @param redisTemplate
     */  
    public void setRedisTemplate(RedisTemplate<String,T> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        @SuppressWarnings("unchecked")
        RedisTemplate<String,T> redisTemplate = applicationContext.getBean(  
                "redisTemplate", RedisTemplate.class);  
        setRedisTemplate(redisTemplate);
    }

}[/mw_shl_code]



Spring-Data-Redis的使用基本最常用 的就是这三种类型value类型、List类型、Set类型。





来源:csdn
作者:请叫我小东子







已有(2)人评论

跳转到指定楼层
梓明 发表于 2017-1-10 11:36:30
mark spring data redis
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条