SpringDataRedis框架入门

SpringDataRedis简介

1.1项目常见问题思考

我们目前的系统已经实现了广告后台管理和广告前台展示,但是对于首页每天有大量的人访问,对数据库造成很大的访问压力,甚至是瘫痪。那如何解决呢?我们通常的做法有两种:一种是数据缓存、一种是网页静态化。我们今天讨论第一种解决方案。

1.2 Redis

redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcache 、memcached 、MongoDB等。

持久化方案:

1、日志模式

(1) 存在脏数据

2、快照模式

(1) 容易导致数据丢失

1.3 Jedis

Jedis是Redis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。可以在Redis官网下载,当然还有一些开源爱好者提供的客户端,如Jredis、SRP等等,推荐使用Jedis。

1.4 Spring Data Redis

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类型的数据操作

1.5 Spring Data Redis入门小Demo

1.5.1准备工作

(1)构建Maven工程 springdataredis-demo

(2)引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>spring-datasolr-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- 缓存 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.0</version>
        </dependency>

        <!--spring-data-redis-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.8.RELEASE</version>
        </dependency>

        <!--test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.12.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

(3)创建spring/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: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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        ">

    <!--加载解析配置文件-->
    <context:property-placeholder location="classpath:redis-config.properties" />

    <!--Jedis连接池配置-->
    <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>

    <!--Jedis连接工厂对象-->
    <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"/>

    <!--Jedis对缓存操作的模板对象-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>

</beans>

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

redis.host=192.168.211.128
redis.port=6379 
redis.pass=
redis.database=0 
redis.maxIdle=300 
redis.maxWait=3000 
redis.testOnBorrow=true 

maxIdle :最大空闲数

maxWaitMillis:连接时的最大等待毫秒数

testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的;

1.5.2值类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-redis.xml")
public class DataRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 增加数据测试
     */
    @Test
    public void testSetValue(){
        redisTemplate.boundValueOps("name").set("itcast");
    }

    /***
     * 查询数据
     */
    @Test
    public void testGetValue(){
        String name = (String) redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

    /**
     * 删除数据
     */
    @Test
    public void testDeleteValue(){
        redisTemplate.delete("name");
    }

1.5.3 Set类型操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/spring-redis.xml")
public class DataRedisSetTest {
    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 增加数据测试
     */
    @Test
    public void testSetValue(){
        redisTemplate.boundSetOps("nameset").add("曹操");
        redisTemplate.boundSetOps("nameset").add("刘备");
        redisTemplate.boundSetOps("nameset").add("孙权");
    }

    /***
     * 查询数据
     */
    @Test
    public void testGetValue(){
        Set members = redisTemplate.boundSetOps("nameset").members();
        System.out.println(members);
    }

    /**
     * 删除数据
     */
    @Test
    public void testDeleteValue(){
        redisTemplate.boundSetOps("nameset").remove("孙权");
    }
}

1.5.4 List类型操作

创建测试类TestList

1.5.4.1 右压栈

/***
 * 增加数据测试
 *  右压栈:后添加的对象排在后边
 */
@Test
public void testSetValueRight(){
    redisTemplate.boundListOps("namelist1").rightPush("刘备");
    redisTemplate.boundListOps("namelist1").rightPush("关羽");
    redisTemplate.boundListOps("namelist1").rightPush("张飞");
}

/***
 * 查询数据
 */
@Test
public void testGetValueRight(){
    List list = redisTemplate.boundListOps("namelist1").range(0, 10);
    System.out.println(list);
}

运行结果:

[刘备, 关羽, 张飞]

1.5.4.2 左压栈

/***
 * 增加数据测试
 *  左压栈:后添加的对象排在前边
 */
@Test
public void testSetValueLeft(){
    redisTemplate.boundListOps("namelist2").leftPush("刘备");
    redisTemplate.boundListOps("namelist2").leftPush("关羽");
    redisTemplate.boundListOps("namelist2").leftPush("张飞");
}

/***
 * 查询数据
 */
@Test
public void testGetValueLeft(){
    List list = redisTemplate.boundListOps("namelist2").range(0, 10);
    System.out.println(list);
}

运行结果:

[张飞, 关羽, 刘备]

1.5.4.3 根据索引查询元素

/**

  • 查询集合某个元素
    */
    @Test
    public void testSearchByIndex(){
    String s = (String) redisTemplate.boundListOps(“namelist1”).index(1);
    System.out.println(s);
    }

1.5.4.4 移除某个元素的值

/**
 * 移除集合某个元素
 */
@Test
public void testRemoveByIndex(){
    redisTemplate.boundListOps("namelist1").remove(1, "关羽");
}

1.5.5 Hash类型操作

创建测试类TestHash

1…5.5.1 存入值

/**
 * 增加数据测试
 */
@Test
public void testSetValue(){
    redisTemplate.boundHashOps("namehash").put("a", "唐僧");
    redisTemplate.boundHashOps("namehash").put("b", "悟空");
    redisTemplate.boundHashOps("namehash").put("c", "八戒");
    redisTemplate.boundHashOps("namehash").put("d", "沙僧");
}

1.5.5.2 提取所有的KEY

/***
 * 提取所有key
 */
@Test
public void testGetKeys(){
    Set s = redisTemplate.boundHashOps("namehash").keys();
    System.out.println(s);
}

运行结果:

[a, b, c, d]

1.5.5.3 提取所有的值

/***
 * 提取所有值
 */
@Test
public void testGetValues(){
    List values = redisTemplate.boundHashOps("namehash").values();
    System.out.println(values);
}

运行结果:

[唐僧, 悟空, 八戒, 沙僧]

1.5.5.4 根据KEY提取值

/***
 * 根据key提取值
 */
@Test
public void testGetValueByKey(){
    Object object = redisTemplate.boundHashOps("namehash").get("b");
    System.out.println(object);
}

运行结果:

悟空

1.5.5.5 根据KEY移除值

/****
 * 根据key移除值
 */
@Test
public void testRemoveValueByKey(){
    redisTemplate.boundHashOps("namehash").delete("c");
}

运行后再次查看集合内容:

[唐僧, 悟空, 沙僧]

posted @ 2021-04-27 11:01  your_棒棒糖  阅读(87)  评论(0编辑  收藏  举报