redis应用学习

一、redis简介:

              1)redis是什么?

               redis本质上是一种键值数据库;但他又具有关系型数据库(支持的存储类型)的一些特点,从而使他介于关系型数据库之间;

               redis不仅支持String类型,还支持Lists(有序)、sets(无序)类型;并且还可以完成排序;

             2)redis一般用来做什么?

               通常局限点来说,Redis也以消息队列的形式存在,作为内嵌的List存在,满足实时的高并发需求。而通常在一个电商类型的数据处理过程之中,有关商品,热销,推荐排序的队列,通常存放在Redis之中,期间也包扩Storm对于Redis列表的读取和更新。

            3)redis的优点是什么?

               --性能极高,redis支持超过100K+每秒的访问频率;

               --丰富的数据类型,redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
               --原子性,Redis的所有操作都是原子性的,同时Redis还支持对几个操作全并后的原子性执行。
               --丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。

             4)redis的缺点是什么?

               --处理海量数据时受到物理内存的限制;不能用作海量数据的高性能读写;
             总结: Redis受限于特定的场景,专注于特定的领域之下,速度相当之快,目前还未找到能替代使用产品。


 二、redis在java中的操作:

        连接池:依赖的jar:jedis-2.1.0.jar和commons-pool-1.5.4.jar

        示例代码如下:

        

package com.test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public final class RedisUtil {
    
    //Redis服务器IP
    private static String ADDR = "192.168.0.100";
    
    //Redis的端口号
    private static int PORT = 6379;
    
    //访问密码
    private static String AUTH = "admin";
    
    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;
    
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;
    
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 10000;
    
    private static int TIMEOUT = 10000;
    
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}

            redis操作字符串:

           

/**
     * redis存储字符串
     */
    @Test
    public void testString() {
        //-----添加数据----------  
        jedis.set("name","xinxin");//向key-->name中放入了value-->xinxin  
        System.out.println(jedis.get("name"));//执行结果:xinxin  
        
        jedis.append("name", " is my lover"); //拼接
        System.out.println(jedis.get("name")); 
        
        jedis.del("name");  //删除某个键
        System.out.println(jedis.get("name"));
        //设置多个键值对
        jedis.mset("name","liuling","age","23","qq","476777XXX");
        jedis.incr("age"); //进行加1操作
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
        
    }

          redis操作Map:

        

 /**
     * redis操作Map
     */
    @Test
    public void testMap() {
        //-----添加数据----------  
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xinxin");
        map.put("age", "22");
        map.put("qq", "123456");
        jedis.hmset("user",map);
        //取出user中的name,执行结果:[minxr]-->注意结果是一个泛型的List  
        //第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数  
        List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
        System.out.println(rsmap);  
  
        //删除map中的某个键值  
        jedis.hdel("user","age");
        System.out.println(jedis.hmget("user", "age")); //因为删除了,所以返回的是null  
        System.out.println(jedis.hlen("user")); //返回key为user的键中存放的值的个数2 
        System.out.println(jedis.exists("user"));//是否存在key为user的记录 返回true  
        System.out.println(jedis.hkeys("user"));//返回map对象中的所有key  
        System.out.println(jedis.hvals("user"));//返回map对象中的所有value 
  
        Iterator<String> iter=jedis.hkeys("user").iterator();  
        while (iter.hasNext()){  
            String key = iter.next();  
            System.out.println(key+":"+jedis.hmget("user",key));  
        }  
    }

 

            redis操作List:

           

 /** 
     * jedis操作List 
     */  
    @Test  
    public void testList(){  
        //开始前,先移除所有的内容  
        jedis.del("java framework");  
        System.out.println(jedis.lrange("java framework",0,-1));  
        //先向key java framework中存放三条数据  
        jedis.lpush("java framework","spring");  
        jedis.lpush("java framework","struts");  
        jedis.lpush("java framework","hibernate");  
        //再取出所有数据jedis.lrange是按范围取出,  
        // 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有  
        System.out.println(jedis.lrange("java framework",0,-1));  
        
        jedis.del("java framework");
        jedis.rpush("java framework","spring");  
        jedis.rpush("java framework","struts");  
        jedis.rpush("java framework","hibernate"); 
        System.out.println(jedis.lrange("java framework",0,-1));
    }  


         redis操作Set:

        

/** 
     * jedis操作Set 
     */  
    @Test  
    public void testSet(){  
        //添加  
        jedis.sadd("user","liuling");  
        jedis.sadd("user","xinxin");  
        jedis.sadd("user","ling");  
        jedis.sadd("user","zhangxinxin");
        jedis.sadd("user","who");  
        //移除noname  
        jedis.srem("user","who");  
        System.out.println(jedis.smembers("user"));//获取所有加入的value  
        System.out.println(jedis.sismember("user", "who"));//判断 who 是否是user集合的元素  
        System.out.println(jedis.srandmember("user"));  
        System.out.println(jedis.scard("user"));//返回集合的元素个数  
    }  


        redis排序:

       

@Test  
    public void test() throws InterruptedException {  
        //jedis 排序  
        //注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的)  
        jedis.del("a");//先清除数据,再加入数据进行测试  
        jedis.rpush("a", "1");  
        jedis.lpush("a","6");  
        jedis.lpush("a","3");  
        jedis.lpush("a","9");  
        System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1]  
        System.out.println(jedis.sort("a")); //[1, 3, 6, 9]  //输入排序后结果  
        System.out.println(jedis.lrange("a",0,-1));  
    }  


三、redis的java客户端的jedis调用方式:

        普通同步方式:

      

@Test
public void test1Normal() {
    Jedis jedis = new Jedis("localhost");
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        String result = jedis.set("n" + i, "n" + i);
    }
    long end = System.currentTimeMillis();
    System.out.println("Simple SET: " + ((end - start)/1000.0) + " seconds");
    jedis.disconnect();
}


       事务方式:确保一个client发起的事务中的命令可以连续的执行,而中间不会插入其他client的命令。

      

@Test
public void test2Trans() {
    Jedis jedis = new Jedis("localhost");
    long start = System.currentTimeMillis();
    Transaction tx = jedis.multi();
    for (int i = 0; i < 100000; i++) {
        tx.set("t" + i, "t" + i);
    }
    List<Object> results = tx.exec();
    long end = System.currentTimeMillis();
    System.out.println("Transaction SET: " + ((end - start)/1000.0) + " seconds");
    jedis.disconnect();
}

      我们调用jedis.watch(…)方法来监控key,如果调用后key值发生变化,则整个事务会执行失败。另外,事务中某个操作失败,并不会回滚其他操作。这一点需要注意。还有,我们可以使用discard()方法来取消事务。

 

      管道:采用异步方式,一次发送多个指令,不同步等待其返回结果。这样可以取得非常好的执行效率;

    

@Test
public void test3Pipelined() {
    Jedis jedis = new Jedis("localhost");
    Pipeline pipeline = jedis.pipelined();
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        pipeline.set("p" + i, "p" + i);
    }
    List<Object> results = pipeline.syncAndReturnAll();
    long end = System.currentTimeMillis();
    System.out.println("Pipelined SET: " + ((end - start)/1000.0) + " seconds");
    jedis.disconnect();
}


     管道中调用事务:

     

@Test
public void test4combPipelineTrans() {
    jedis = new Jedis("localhost"); 
    long start = System.currentTimeMillis();
    Pipeline pipeline = jedis.pipelined();
    pipeline.multi();
    for (int i = 0; i < 100000; i++) {
        pipeline.set("" + i, "" + i);
    }
    pipeline.exec();
    List<Object> results = pipeline.syncAndReturnAll();
    long end = System.currentTimeMillis();
    System.out.println("Pipelined transaction: " + ((end - start)/1000.0) + " seconds");
    jedis.disconnect();
}


     分布式直连同步调用:

  

@Test
public void test5shardNormal() {
    List<JedisShardInfo> shards = Arrays.asList(
            new JedisShardInfo("localhost",6379),
            new JedisShardInfo("localhost",6380));

    ShardedJedis sharding = new ShardedJedis(shards);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        String result = sharding.set("sn" + i, "n" + i);
    }
    long end = System.currentTimeMillis();
    System.out.println("Simple@Sharing SET: " + ((end - start)/1000.0) + " seconds");

    sharding.disconnect();
}


      分布式直连异步调用:

   

@Test
public void test6shardpipelined() {
    List<JedisShardInfo> shards = Arrays.asList(
            new JedisShardInfo("localhost",6379),
            new JedisShardInfo("localhost",6380));

    ShardedJedis sharding = new ShardedJedis(shards);

    ShardedJedisPipeline pipeline = sharding.pipelined();
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        pipeline.set("sp" + i, "p" + i);
    }
    List<Object> results = pipeline.syncAndReturnAll();
    long end = System.currentTimeMillis();
    System.out.println("Pipelined@Sharing SET: " + ((end - start)/1000.0) + " seconds");

    sharding.disconnect();
}


      分布式连接池同步调用:如果,你的分布式调用代码是运行在线程中,那么上面两个直连调用方式就不合适了,因为直连方式是非线程安全的,这个时候,你就必须选择连接池调用。

     

@Test
public void test7shardSimplePool() {
    List<JedisShardInfo> shards = Arrays.asList(
            new JedisShardInfo("localhost",6379),
            new JedisShardInfo("localhost",6380));

    ShardedJedisPool pool = new ShardedJedisPool(new JedisPoolConfig(), shards);

    ShardedJedis one = pool.getResource();

    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        String result = one.set("spn" + i, "n" + i);
    }
    long end = System.currentTimeMillis();
    pool.returnResource(one);
    System.out.println("Simple@Pool SET: " + ((end - start)/1000.0) + " seconds");

    pool.destroy();
}


      分布式连接池异步调用:

    

@Test
public void test8shardPipelinedPool() {
    List<JedisShardInfo> shards = Arrays.asList(
            new JedisShardInfo("localhost",6379),
            new JedisShardInfo("localhost",6380));

    ShardedJedisPool pool = new ShardedJedisPool(new JedisPoolConfig(), shards);

    ShardedJedis one = pool.getResource();

    ShardedJedisPipeline pipeline = one.pipelined();

    long start = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        pipeline.set("sppn" + i, "n" + i);
    }
    List<Object> results = pipeline.syncAndReturnAll();
    long end = System.currentTimeMillis();
    pool.returnResource(one);
    System.out.println("Pipelined@Pool SET: " + ((end - start)/1000.0) + " seconds");
    pool.destroy();
}

 

四、注意:

     1、事务和管道都是异步模式。在事务和管道中不能同步查询结果。比如下面两个调用,都是不允许的:

Transaction tx = jedis.multi();
 for (int i = 0; i < 100000; i++) {
     tx.set("t" + i, "t" + i);
 }
 System.out.println(tx.get("t1000").get());  //不允许

 List<Object> results = tx.exec();

 …
 …

 Pipeline pipeline = jedis.pipelined();
 long start = System.currentTimeMillis();
 for (int i = 0; i < 100000; i++) {
     pipeline.set("p" + i, "p" + i);
 }
 System.out.println(pipeline.get("p1000").get()); //不允许

 List<Object> results = pipeline.syncAndReturnAll();

 

        2、事务和管道都是异步的,个人感觉,在管道中再进行事务调用,没有必要,不如直接进行事务模式。

        3、分布式中,连接池的性能比直连的性能略好。

        4、分布式调用中不支持事务。
五、在spring中的集成:

       需要的jar包:

       jedis-2.9.0.jar

       commons-pool2-2.4.2.jar

       spring.jar

       jar包链接: https://pan.baidu.com/s/1jIbY7vK 密码: cgjd

       配置文件:

      

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	  xmlns:context="http://www.springframework.org/schema/context"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
  
	  <!-- 加载redis配置文件 -->
	  <context:property-placeholder location="classpath*:profile/redis.properties"/>
	  
	  <!-- redis连接池的配置 -->
	  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		  <property name="maxTotal" value="${redis.pool.maxActive}"/>
		  <property name="maxIdle" value="${redis.pool.maxIdle}"/>
		  <property name="minIdle" value="${redis.pool.minIdle}"/>
		  <property name="maxWaitMillis" value="${redis.pool.maxWait}"/>
		  <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
		  <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
	  </bean> 
	  
	  <!-- redis的连接池pool,不是必选项:timeout/password -->
	  <bean id = "jedisPool" class="redis.clients.jedis.JedisPool">
		  <constructor-arg index="0" ref="jedisPoolConfig"/>
		  <constructor-arg index="1" value="${redis.host}"/>
		  <constructor-arg index="2" value="${redis.port}" type="int"/>
		  <constructor-arg index="3" value="${redis.timeout}" type="int"/>
		 <!-- <constructor-arg index="4" value="${redis.password}"/>  -->
	  </bean>
	  
  </beans>


需要注意的是在新版本的jedis-2.9.0.jar中,没有属性maxactive和maxWait ,相应的换成了maxTotal和maxWaitMillis;另外配置文件的加载实际上以来的是org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;采用的是扫描反射机制;示例代码如下

#mongo加载资源文件
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:mongodb.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" /> 
	</bean>

#redis加载资源文件
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath*:redis.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true" /> 
	</bean>


 


 

              

                       

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
### 回答1: 以下是Redis中文学习资料: 1. Redis官方网站:https://redis.io/documentation 2. Redis中文网:http://www.redis.cn/documentation.html 3. Redis命令参考手册:http://redisdoc.com/ 4. Redis设计与实现(第一版):http://redisbook.com/index.html 5. Redis设计与实现(第二版):https://redisbook.readthedocs.io/en/latest/index.html 6. Redis实战:http://redisinaction.com/ 7. Redis入门指南:https://www.runoob.com/redis/redis-tutorial.html 8. Redis高可用性架构:https://github.com/huangz1990/redis-ha/blob/master/README.md 9. Redis集群搭建指南:https://blog.csdn.net/ddw120533/article/details/86370577 10. Redis分布式锁实现:https://www.cnblogs.com/linjiqin/p/redisLock.html 希望这些资料能够帮到你对Redis学习和理解。 ### 回答2: Redis是一款开源的内存数据存储系统,广泛应用于缓存、消息队列、排行榜、实时统计等场景。目前,已经有一些优质的中文学习资料可供参考。 首先,可以从Redis官方文档入手,Redis官方文档提供了详尽的中文版,其中包括了Redis的安装、配置、数据结构、命令等方面的内容,对于初学者来说是非常全面和详尽的学习资料。 此外,还有一些Redis的中文教程和博客文章,通过搜索引擎可以找到很多。一些知名的技术博主或专业培训机构也会发布关于Redis的中文学习资料,深入浅出地介绍Redis的原理、使用方法和应用实践,通过阅读这些资料,可以更好地理解和应用Redis。 同时,还有很多Redis的中文书籍可供学习,比如《Redis深度历险:核心原理与应用实践》、《Redis设计与实现》等。这些书籍通常会从理论和实践两个层面进行讲解,既能够帮助读者理解Redis的设计原理,又能够通过实例帮助读者掌握Redis的具体使用方法。 此外,对于想要深入研究Redis的开发者,Redis的源码是不可或缺的学习资料。通过阅读Redis的源码,可以更加深入地了解Redis的实现细节和性能优化技巧。 总而言之,Redis的中文学习资料丰富多样,无论是官方文档、教程博客、书籍还是源码,都能够帮助读者系统全面地学习应用Redis

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值