Spring-data-redis入门

1.简介

Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

spring-data-redis针对jedis提供了如下功能:

1.连接池自动管理,提供了一个高度封装的“RedisTemplate”类

2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口

ValueOperations:简单K-V操作
​
SetOperations:set类型数据操作
​
ZSetOperations:zset类型数据操作
​
HashOperations:针对map类型的数据操作
​
ListOperations:针对list类型的数据操作

2.入门小Demo

1.准备工作

(1)构建Maven工程

(2)引入Spring相关依赖、引入JUnit依赖

(3)引入Jedis和SpringDataRedis依赖

<properties>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>
​
    <dependencies>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.7.2.RELEASE</version>
    </dependency>
​
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>
    </dependencies>

(4)在src/main/resources下创建properties文件夹,建立redis-config.properties

# Redis settings 
# server IP 
redis.host=127.0.0.1
# server port 
redis.port=6379
# server pass 
redis.pass=
# use dbIndex 
redis.database=0
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 
redis.maxIdle=300
# 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException;  
redis.maxWait=3000
# 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的  
redis.testOnBorrow=true

(5)在src/main/resources下创建spring文件夹 ,创建applicationContext-redis.xml

<context:property-placeholder location="classpath*:properties/redis-config.properties" />
    <!-- redis 相关配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
​
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>

2.值类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestValue {
​
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存值
     */
    @Test
    public void setValue(){
        redisTemplate.boundValueOps("name").set("redis");
    }
​
    /**
     * 取值
     */
    @Test
    public void getValue(){
        System.out.println(redisTemplate.boundValueOps("name").get());
    }
​
    /**
     * 删除
     */
    @Test
    public void delValue(){
        redisTemplate.delete("name");
    }
}

3.set

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestSet {
​
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存值
     */
    @Test
    public void setValue(){
        redisTemplate.boundSetOps("books").add("西游记");
        redisTemplate.boundSetOps("books").add("三国演义");
        redisTemplate.boundSetOps("books").add("红楼梦");
        redisTemplate.boundSetOps("books").add("水浒传");
    }
​
    /**
     * 取值
     * set类型为无序的,存取顺序不一致
     */
    @Test
    public void getValue(){
        Set books = redisTemplate.boundSetOps("books").members();
        System.out.println(books); //[西游记, 水浒传, 红楼梦, 三国演义]
    }
​
    /**
     * 删除集合中的某个值
     */
    @Test
    public void deleValue(){
        redisTemplate.boundSetOps("books").remove("西游记");
    }
​
    /**
     * 删除整个集合
     */
    @Test
    public void deleAll(){
        redisTemplate.delete("books");
    }
}

4.List类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestList {
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 右压栈:后添加的对象排在后边
     */
    @Test
    public void setValue() {
        redisTemplate.boundListOps("nameList").rightPush("刘备");
        redisTemplate.boundListOps("nameList").rightPush("关羽");
        redisTemplate.boundListOps("nameList").rightPush("张飞");
    }
​
    /**
     * 显示右压栈集合
     */
    @Test
    public void getValue() {
        //range(long start,long end)
        //start表示开始的索引,end表示要遍历的长度
        List nameList = redisTemplate.boundListOps("nameList").range(0, 3);
        System.out.println(nameList);   //[刘备, 关羽, 赵飞]
    }
​
    /**
     * 左压栈:先添加的对象排在后边
     */
    @Test
    public void setValue1() {
        redisTemplate.boundListOps("nameList1").leftPush("宋江");
        redisTemplate.boundListOps("nameList1").leftPush("武松");
        redisTemplate.boundListOps("nameList1").leftPush("鲁智深");
    }
​
    /**
     * 显示左压栈集合
     */
    @Test
    public void getValue1() {
        List nameList = redisTemplate.boundListOps("nameList1").range(0, 3);
        System.out.println(nameList);   //[鲁智深, 武松, 宋江]
    }
​
    /**
     * 查询某个结果
     */
    @Test
    public void getSerarchByIndex() {
        Object o = redisTemplate.boundListOps("nameList").index(1);
        System.out.println(o);  //关羽
    }
​
    /**
     * 移除集合中的某个元素
     */
    @Test
    public void removeByIndex() {
        //remove(long i,Object value)
        //i表示要删除的元素个数,value表示要删除的元素
        //此处表示删除1个鲁智深
        redisTemplate.boundListOps("nameList1").remove(1, "鲁智深");
    }
}
​

5.Hash类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext-redis.xml")
public class TestHash {
    @Autowired
    private RedisTemplate redisTemplate;
​
    /**
     * 存入值
     */
    @Test
    public void setValue(){
        redisTemplate.boundHashOps("city").put("山西","太原");
        redisTemplate.boundHashOps("city").put("河北","石家庄");
        redisTemplate.boundHashOps("city").put("浙江","杭州");
        redisTemplate.boundHashOps("city").put("山东","青岛");
        redisTemplate.boundHashOps("city").put("内蒙古","呼和浩特");
    }
​
    /**
     * 获取所有的key
     */
    @Test
    public void getKeys(){
        Set cityKey = redisTemplate.boundHashOps("city").keys();
        System.out.println(cityKey);
    }
​
    /**
     * 获取所有的value
     */
    @Test
    public void getValues(){
        List cityValue = redisTemplate.boundHashOps("city").values();
        System.out.println(cityValue);
    }
​
    /**
     * 获取指定的value
     */
​
    @Test
    public void getValue(){
        Object o = redisTemplate.boundHashOps("city").get("山西");
        System.out.println(o);
    }
​
    /**
     * 根据key移除value
     */
​
    @Test
    public void delete(){
        redisTemplate.boundHashOps("city").delete("内蒙古");
    }
}
​

猜你喜欢

转载自blog.csdn.net/fy_java1995/article/details/84861534