Home > Database > Mysql Tutorial > MySQL redis learning and application

MySQL redis learning and application

黄舟
Release: 2017-02-28 13:22:17
Original
2035 people have browsed it

Relational databases such as mysql have limited read and write performance when data is stored in high concurrency situations. Nosql (non-relational database) emerged as the times require to make up for the problem. overcome the shortcomings of relational databases.

【Introduction】

## redis is a key-value storage form Nosql database is widely used. It supports master-slave replication, transaction processing, optimistic locking, complex transaction control, persistence, publishing and subscribing messages and other features.

##[Introduction to data types]

The data type of redis is simpler than that of relational database, and is divided into 5 major types: string, hashs, lists, sets, and sorted set.

1. The string type is a binary, safe data type that can store jps images or serialized pairs. Commonly used redis database commands are:

<span style="font-family:KaiTi_GB2312;">		
</span>
<span style="font-family:SimSun;">a. Set name lijie ----设置name=lijie
		b. Setnx 设置如果name存在,则返回0,设置不成功(nx--not exit)
		c. Setex 指定有效期:set haircolor 10 red   --10秒失效
		d. Setrange name 6 gmail.com  ----从第6个开始设置
		e. Mset key1 lijie1 key2 lijei2 key3 lijie3 --设置多个键值对
		f.  get --获得字符
		g. Getrange eamil 0 5  从下标为0到5的值
		h. Mget--批量返回
		i. Incr key6 --自增
		j. Incrby key5 6--以6来进行自增
		k. Decr/decrby
		l. Append key1 .net 在key1后面增加.net
		m. Strlen--返回长度</span><span style="font-family:KaiTi_GB2312;">
</span>
Copy after login

2. The hash type takes up less memory, commonly used commands:


		  <span style="font-family:SimSun;">a. Hset--hset user:001 name lijie
		b. Hsetnx--hsetnx user:002 name lamp
		c. Hmset---hmset user:003 name lijie age 20 sex 1
		d. Hincrby--自增
		e. Hexists--判断是否存在 hexits user:002 name
		f. Hlen----返回所有键数量
		g. Hdel--hdel user:003 age
		h. Hkeys --hkeys user:001
		i. Hvals---hvals user:003
		j. Hgetall---获取所有fileds和value</span>
Copy after login

3. The lists data type is divided into two data structures: linked list structure and queue. Common commands:


		<span style="font-family:SimSun;">a. Lpush--从头部压入元素:lpush list1 "hello"--栈
		b. Lrang myliist 0 -1  从头部一直去不到尾部
		c. Rpush---rpush list2 "hello"---队列
		d. Linsert---linsert list2 before hello word
		e. Lset--指定下标赋值:lset list2 1 my
		f. Lrem--从list 中删除n个和value相同的值
		g. Ipop从头弹出元素
		h. Rpop 从尾部
		i. Rpoplpush
		j. Lindex---lindex list2 2
		k. Llen---返回长度</span>
Copy after login

4. The sets type supports union, intersection, cross set and other operations. Use the command:


		<span style="font-family:SimSun;">a. Sadd--sadd myset1 one
		b. Smembers--查看
		c. Srem --srem myset2 "one"
		d. Spop--随机弹出
		e. Sdiff--两个集合的差集  
		f. Sdiffstor---叉集存储到指定sets里面:sdiffstore myset4 myset2 myset3
		g. Siner--返回交集/sinnerstore
		h. Sunion--并集/
		i. Smove---将第一个set中元素剪切到第二个set中 smove myset1 myset8 three
		j. Scard --查看个数
		k. Sismemeber---测试元素是不是set中元素
		l. Srandmember--随机返回元素不会删除</span>
Copy after login

5. Sort set is an ordered set:


		<span style="font-family:SimSun;">a. Zadd---zadd myzset “one”
		b. 取值:zrange myzet 0 -1 withscores(显示顺序)
		c. Zrem--zrem myzset two
		d. Zincrby--zincrby sset1 2 one--对顺序号进行增加
		e. Zrank--返回 索引:zrank myset3 two
		f. Zrevrank
		g. Zrerange--降序排序
		h. Zrangebyscore--按照范围返回:zrangebyscore sset2 2 4 with scores
		i. Zcount--返回数量 zcount seet2 2 4
		j. Zcard --返回 
		k. Zremrangebyrank--按照索引删除
		l. Zremrangebyscore--按照顺序删除</span>
Copy after login

【java application】

Redis in Java needs to introduce jar package: Import Redis.clients.jedis.jedis; # Use directly in the code: Jedis client=new Jedis("ip address",6379);, which can realize redis connection. When using the connection pool, create a connection pool class:

package com.tgb.itoo.exam.students.controller;

import java.util.ResourceBundle;

import org.springframework.util.Assert;

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

public class JedisPoolTest {
	private static JedisPool jedisPool;
	
	private static JedisPoolConfig initPoolConfig(){
		 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();  
	     // 控制一个pool最多有多少个可用的的jedis实例  
//	     jedisPoolConfig.setMaxActive(1000);   
	        // 最大能够保持空闲状态的对象数  
	     jedisPoolConfig.setMaxIdle(300);  
	        // 超时时间  
	     jedisPoolConfig.setMaxWaitMillis(1000);  
	        // 在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;  
	     jedisPoolConfig.setTestOnBorrow(true);   
	        // 在还会给pool时,是否提前进行validate操作  
	     jedisPoolConfig.setTestOnReturn(true);  
	     return jedisPoolConfig;  
	}
	
	 /** 
     * 初始化jedis连接池 
     * <br>------------------------------<br> 
     */  
      
    public static void before() {  
        JedisPoolConfig jedisPoolConfig = initPoolConfig();    
        // 属性文件读取参数信息  
        ResourceBundle bundle = ResourceBundle.getBundle("redis_config");  
        String host = bundle.getString("redis.host");  
        int port = Integer.valueOf(bundle.getString("redis.port"));  
        int timeout = Integer.valueOf(bundle.getString("redis.timeout"));  
        String password = bundle.getString("redis.password");  
        // 构造连接池  
        jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);  
    }  
    

    public void testSet() {  
        Jedis jedis = null;   
        // 从池中获取一个jedis实例  
        try {  
            jedis = jedisPool.getResource();  
            jedis.set("blog_pool", "java2000_wl");  
        } catch (Exception e) {  
            // 销毁对象  
            jedisPool.returnBrokenResource(jedis);  
//            Assert.fail(e.getMessage());  
        } finally {  
            // 还会到连接池  
            jedisPool.returnResource(jedis);  
        }  
    }    
}
Copy after login

Pipeline Technology Application


##redis When performing continuous write operations , in order to reduce the number of times the database is opened and closed, creating a pipeline can improve performance. Actual use:


##

                Pipeline pipeline=client.pipelined();
		
		for (TemplateDetail templateDetail : templateDetails) {
			List<QuestionMain> questionMains=templateDetail.getQuestionMainList();
			for (QuestionMain questionMain : questionMains) {
				if(null!=questionMain){
				String redisKey=studenInfo.getStudentId()+"_"+studenInfo.getExamination_id()+"_"+questionMain.getId()+"_exam";
				
				try {
					pipeline.lpush(redisKey,JsonUtils.objectToJson(questionMain));
					pipeline.expire(redisKey, 7200);
				} catch (IOException e) {	
					e.printStackTrace();
				}				
				}
			}			
		}
		pipeline.sync();//管道执行
Copy after login

The above is the learning and application of MySQL redis Content, please pay attention to the PHP Chinese website (m.sbmmt.com) for more related content!




#
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template