• Redis和SpringDataRedis


    一.Redis简介

      Redis是用C语言开发的一个开源的高性能键值对(key-value)数据库,运行在内存中,由ANSI C编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcache 、memcached 、MongoDB等。

    1.Redis数据结构

    ​ 字符串类型 string 散列类型 hash 列表类型 list 有序可重复 集合类型 set 无序不可重复 有序集合类型 sortedset 有序不可重复

    2.Redis应用场景

    做缓存: 缓存的是使用频次较高,但不是特别重要的数据,请求来时,优先查询非关系型数据库,如果没有查到则查询关系型数据库,从关系型数据库中查询到结果后,将结果存放到非关系型数据库中,并将结果返回给浏览器.如果查询到了,直接将查询结果返回给浏览器即可。

    当用户执行 增 删 改操作时,优先操作关系型数据库, (会造成Redis数据丢失)

    操作完毕后,删除非关系型数据库中的相关数据. (需要Redis数据同步)

    二.Redis持久化:

    注意: 要想使用redis的持久化操作,启动redis时必须采用配置文件

    使用指定配置文件开启服务 (会持久化) ★★★★★

    启动服务器: 在dos命令中输入 redis-server.exe redis.windows.conf

    启动客户端: 在dos命令中输入 redis-cli.exe

    1.RDB持久化方式: (默认)

    rdb方式在持久化数据时,采用快照机制.

    执行快照保存的时机:

    save 900 1 save 300 10 save 60 10000

    存在问题: 可能导致数据丢失

    在redis的配置文件中已经定义好使用rdb方式进行持久化了,将持久化的数据存放在当前目录的dump.rdb.

    redis服务器正常关闭时也会执行持久化操作(快照保存数据)

    2.AOF持久化方式:

    持久化的是执行过程,每一条命令都会持久化保存

    使用方式:

    1.开启AOF持久化(修改配置文件)

    将配置文件中的 appendonly 改为 yes

    appendfsync always (我们使用的)

    # appendfsync everysec

    # appendfsync no

    特点:

    不会导致数据丢失.

    性能低

    三. Jedis

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

    • jdbc: java操作mysql数据的方式

    • jedis: java操作redis数据库的方式

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

    五.Spring Data Redis操作Redis数据库

    第一步:导入相关坐标到Spring项目中

    <!-- Redis缓存相关坐标 -->
    <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>

    第二步:在resources下编写redis的配置文件

    resources/redis-config.properties

    # Redis settings 
    # server IP 
    redis.host=192.168.25.130
    # server port 
    redis.port=6379
    # server pass 
    redis.pass=
    # use dbIndex 
    redis.database=0
    # maxIdle
    redis.maxIdle=300
    # maxWait
    redis.maxWait=3000
    # testOnBorrow
    redis.testOnBorrow=true

    resources/applicationContext-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">
    
        <!-- 1.加载外部配置文件 -->
        <context:property-placeholder location="classpath*:properties/*.properties"/>
    
        <!-- 2.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>
    
        <!-- 3.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"/>
    
        <!-- 4.redis模板的配置 -->
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="JedisConnectionFactory"/>
        </bean>
    
    </beans>  

    第三步:使用redisTemplate模板操作数据库

    1.操作String类型数据

    /**
     * @author Mr.song
     * @date 2019/06/12 21:09
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/applicationContext-redis.xml")
    public class RedisStrTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void testSetString(){
            //模板绑定存储的数据类型为String并存入数据: key是testStr   value是DinTalk
            redisTemplate.boundValueOps("testStr").set("DinTalk");
        }
    
        @Test
        public void testGetString(){
            //模板绑定存储的数据类型为String并取数据:使用key testStr
            String testStr = (String) redisTemplate.boundValueOps("testStr").get();
            System.out.println(testStr);
        }
    
        @Test
        public void testDelString(){
            //直接用模板根据key删除数据,删除后无数据查询返回null
            redisTemplate.delete("testStr");
        }
    
        //使用相同的key重新设置值便是更新
    }

    2.操作List类型数据

    /**
     * @author Mr.song
     * @date 2019/06/12 21:22
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/applicationContext-redis.xml")
    public class RedisListTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void testSetList(){
            //模板绑定存储的数据类型为List并存入数据:key是myList,List的数据类型,数据为din.....
            redisTemplate.boundListOps("myList").leftPush("din");
            redisTemplate.boundListOps("myList").leftPush("talk");
            redisTemplate.boundListOps("myList").leftPush("cn");
        }
    
        @Test
        public void testGetList(){
            //模板绑定存储的数据类型为List并取数据:key是myList,rang中0是开始,-1是全部
            List myList = redisTemplate.boundListOps("myList").range(0, -1);
            myList.stream().forEach(System.out::println);
            //取list中的一个数据 :先进先出(相当于弹出-删除了)
            //String myList = (String) redisTemplate.boundListOps("myList").rightPop();
            //System.out.println(myList); //din
        }
    
        @Test
        public void testDelList(){
            //直接用模板根据key删除数据(删除整个集合)
            redisTemplate.delete("myList");
            //指定删除list的数据 :删除一个talk
            //redisTemplate.boundListOps("myList").remove(1,"talk");
        }
    
        //使用相同的key重新设置值便是更新
    }

    3.操作Set类型数据

    /**
     * @author Mr.song
     * @date 2019/06/12 21:09
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/applicationContext-redis.xml")
    public class RedisSetTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void testSetValue(){
            //模板绑定存储的数据类型为Set并存入数据: key是mySet   value是din talk 等
            redisTemplate.boundSetOps("mySet").add("www");
            redisTemplate.boundSetOps("mySet").add("din");
            redisTemplate.boundSetOps("mySet").add("talk");
            redisTemplate.boundSetOps("mySet").add("cn");
        }
    
        @Test
        public void testGetValue(){
            //模板绑定存储的数据类型为Set并取数据:使用key为 mySet
            Set mySet = redisTemplate.boundSetOps("mySet").members();
            mySet.stream().forEach(System.out::println);
        }
    
        @Test
        public void testDelValue(){
            //直接用模板根据key删除数据,删除整个Set集合
            redisTemplate.delete("mySet");
            //redisTemplate.boundSetOps("mySet").remove("www");
        }
    
        //使用相同的key重新设置值便是更新
    }

    4.操作ZSet类型数据

    /**
     * @author Mr.song
     * @date 2019/06/12 21:09
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/applicationContext-redis.xml")
    public class RedisZSetTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        //ZSet集合有序,数据有分值
        @Test
        public void testSetValue(){
            //模板绑定存储的数据类型为Set并存入数据: key是myZSet  value是din talk 等,各有分值
           redisTemplate.boundZSetOps("myZSet").add("din",15);
           redisTemplate.boundZSetOps("myZSet").add("talk",55);
           redisTemplate.boundZSetOps("myZSet").add("www",25);
           redisTemplate.boundZSetOps("myZSet").add("cn",45);
        }
    
        @Test
        public void testGetValue(){
            //1.模板绑定存储的数据类型为ZSet并取数据:使用key为 myZSet(取一定分值范围的)
            //Set myZSet = redisTemplate.boundZSetOps("myZSet").rangeByScore(20, 50);
            //myZSet.stream().forEach(System.out::println);
            //2.取全部的
            //Set myZSet = redisTemplate.boundZSetOps("myZSet").range(0, -1);
            //myZSet.stream().forEach(System.out::println);
            //3.取数据,带分值
            Set<DefaultTypedTuple> myZSet = redisTemplate.boundZSetOps("myZSet").rangeWithScores(0, -1);
            for (DefaultTypedTuple defaultTypedTuple : myZSet) {
                System.out.println(defaultTypedTuple.getValue());//数据
                System.out.println(defaultTypedTuple.getScore());//分值
            }
        }
    
        @Test
        public void testDelValue(){
            //1.直接用模板根据key删除数据,删除整个ZSet集合
            //redisTemplate.delete("myZSet");
            //2.删除部分数据
            redisTemplate.boundZSetOps("myZSet").removeRangeByScore(15,25);
        }
    
        //使用相同的key重新设置值便是更新
    }

    5.操作Hash类型数据

    /**
     * @author Mr.song
     * @date 2019/06/12 21:09
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:spring/applicationContext-redis.xml")
    public class RedisHashTest {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Test
        public void testSetHash(){
            //模板绑定存储的数据类型为Hash并存入数据: key是myHash value是{din:叮}等键值对
            redisTemplate.boundHashOps("myHash").put("din","叮");
            redisTemplate.boundHashOps("myHash").put("talk","当");
            redisTemplate.boundHashOps("myHash").put("song","宋");
            redisTemplate.boundHashOps("myHash").put("hui","慧");
        }
    
        @Test
        public void testGetHash(){
            //模板绑定存储的数据类型为Hash并取数据:使用key为 myHash,获取键的集合
            //Set myHash = redisTemplate.boundHashOps("myHash").keys();
            //myHash.stream().forEach(System.out::println);
            //获取value的集合(值可重复,所以是list)
            //List myHash = redisTemplate.boundHashOps("myHash").values();
            //myHash.stream().forEach(System.out::println);
            //使用myHash这个key获取到Hash并用键获取值
            String s = (String) redisTemplate.boundHashOps("myHash").get("din");
            System.out.println(s);
        }
    
        @Test
        public void testDelHash(){
            //直接用模板根据key删除数据,删除整个Hash集合
            //redisTemplate.delete("myHash");
            redisTemplate.boundHashOps("myHash").delete("din");
        }
    
        //使用相同的key重新设置值便是更新
    }

    附录1:Linux系统中安装Redis Server

    1. 将redis资源包上传到Linux中
    2. 执行tar -zxvf redis-3.0.0.tar.gz解压
    3. 创建/usr/local/redis目录, //命令 mkdir redis
    4. 进入解压的redis-3.0.0,安装redis服务,执行命令:make install PREFIX=/usr/local/redis
    5. 复制配置文件将/redis-3.0.0/redis.conf 复制到redis 下的bin 目录下  执行命令:
       cp redis.conf /usr/local/redis-cluster/redis-1/bin/
    6.启动redis服务

    关注微信公众号,随时随地学习

  • 相关阅读:
    申论1
    why factory pattern and when to use factory pattern
    jvm的字符串池
    is assembler instruction and machine instuction atomic
    jvm本身的多线程机制
    final
    java类的加载
    path和classpath的用途
    jar -cmf file1 file2 file3命令
    MANIFEST.MF中的MF是什么意思
  • 原文地址:https://www.cnblogs.com/dintalk/p/11016061.html
Copyright © 2020-2023  润新知