Review and finish the basic application of 7:redis database

Source: Internet
Author: User
Tags connection pooling

One: Learn about NoSQL

1: Introduction: The full name of NoSQL is not-only SQL, the concept was raised early on, in 09 when the comparison of fire. NoSQL refers to a non-relational database, and we often use relational databases. Like our usual mysql,sqlserver, these databases are typically used to store important information, and there's no problem with normal business. However, with the rapid development of the Internet, the traditional relational database in dealing with ultra-large-scale, ultra-large traffic and high concurrency when the time is inadequate. And just at this time, NoSQL gets to tell the development.

The difference between 2:nosql and relational databases:

(1) Storage: Relational databases are tabular, so they are stored in the rows and columns of the table. They are easily associated with collaborative storage, and extracting data is easy. The NoSQL database, in contrast, is a chunk of the combination. It is usually stored in a dataset, like a document, a key-value pair, or a graph structure. Redis is stored as a key-value pair.

(2) Storage structure: Relational database pre-defined structure brings reliability and stability, but it is difficult to modify this data. and NoSQL databases are based on dynamic structures, using and unstructured data. Because NoSQL databases are dynamic structures, it is easy to adapt to changes in data types and structures.

(3) Performance: relational databases maintain data stability and consistency, while NoSQL storage is highly efficient compared to relational databases when confronted with massive amounts of data.

(4) slightly

Four categories of 3:nosql

1. Key value (Key-value) storage, such as Redis (advantage: Fast query Disadvantage: Storage data is missing structured)

2. Columnstore, such as HBase (advantage: Fast query, extensibility, strong disadvantage: relative limitation of function)

3. Documentation database, such as MONGODB (advantage: Data structure requirements are not strict disadvantage: query performance is not high, indeed unified query syntax)

4. Graphic databases, such as Infogrid (advantages: Using graph structure-related algorithms disadvantage: need to calculate the entire graph to get results, not easy to do distributed cluster scheme)

II: Redis Learning:

1: Introduction: A NoSQL (not only SQL) database, mainly in the form of key values (Key-value) to store data, the supported key-value data types are

1 String type,

2 List type lists,

3 ordered set type Zset,

4 Hash type hash,

5 collection type set,

The application scenarios are cache, leaderboard, Task queue, website access statistics, data expiration processing, session separation in distributed cluster architecture.

2: Install: Linux, decompression installation, background boot The operation is simple and is basically consistent with other software installations.

Three: Using Jedis to operate Redis

1 Introduction: Jedis is the official Redis preferred Java Client Development package

Jedis Source Project Address:

HTTPS://GITHUB.COM/XETORTHIO/JEDIS2: Use: To use Jedis you must load the jar package or add Maven dependencies. Add the following statement in the Pom.xml
1 <Dependency>2     <groupId>Redis.clients</groupId>3     <Artifactid>Jedis</Artifactid>4     <version>2.9.0</version>5     <type>Jar</type>6     <Scope>Compile</Scope>7 </Dependency>

Jedis of course also supports the connection pool, the benefit of the connection pool I will not mention, I will say how to use:

First, the configuration parameters are extracted to write the redis.properties file. For example:

1 #*****************jedis Connection parameter settings *********************2 #redis服务器ip3 redis.ip=xxx.xxx.xxx.xxx4 #redis服务器端口号5 redis.port=63796 #redis访问密码7 redis.password=1234568 #与服务器建立连接的超时时间9 redis.timeout=3000Ten #************************jedis Pool parameter settings ******************* One #jedis的最大活跃连接数 A jedis.pool.maxactive=100 - #jedis最大空闲连接数 - jedis.pool.maxidle=50 the #jedis池没有连接对象返回时, the maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out.  - #如果超过等待时间, the jedisconnectionexception is thrown directly - jedis.pool.maxwait=1500 - #从池中获取连接的时候, whether a valid check is performed + jedis.pool.testonborrow=true - #归还连接的时候, whether a valid check is performed +Jedis.pool.testonreturn=true

Writing Redis connection Pooling Tool class Redispoolutil, there are other versions on the Web, in fact, the essence of implementation is the same

1 Importjava.util.Properties;2 ImportRedis.clients.jedis.Jedis;3 ImportRedis.clients.jedis.JedisPool;4 ImportRedis.clients.jedis.JedisPoolConfig;5  6 /**7 * Redis connection Pooling Tool class8  */9  Public classRedispoolutil {Ten     Private StaticJedispool Jedispool =NULL; One     Private StaticString redisconfigfile = "Redis.properties"; A     //Place the Redis connection object in a local thread -     Private StaticThreadlocal<jedis> local=NewThreadlocal<jedis>(); -      the     //do not allow instances of this class to be created from new -     PrivateRedispoolutil () { -     } -   +     /** - * Initializing Redis connection pool +      */ A      Public Static voidInitialpool () { at         Try { -Properties props =NewProperties (); -             //To load a connection pool configuration file -Props.load (Redispoolutil.class. getClassLoader (). getResourceAsStream (Redisconfigfile)); -             //To create a Jedis pool configuration instance -Jedispoolconfig config =Newjedispoolconfig (); in             //Set Pool configuration item values -Config.setmaxtotal (Integer.valueof (Props.getproperty ("Jedis.pool.maxActive"))); toConfig.setmaxidle (Integer.valueof (Props.getproperty ("Jedis.pool.maxIdle"))); +Config.setmaxwaitmillis (Long.valueof (Props.getproperty ("jedis.pool.maxWait"))); -Config.settestonborrow (Boolean.valueof (Props.getproperty ("Jedis.pool.testOnBorrow"))); theConfig.settestonreturn (Boolean.valueof (Props.getproperty ("Jedis.pool.testOnReturn"))); *             //instantiate a Jedis pool based on configuration $Jedispool =NewJedispool (config, props.getproperty ("Redis.ip"),Panax NotoginsengInteger.valueof (Props.getproperty ("Redis.port")), -Integer.valueof (Props.getproperty ("Redis.timeout")), theProps.getproperty ("Redis.password")); +SYSTEM.OUT.PRINTLN ("thread pool was successfully initialized"); A}Catch(Exception e) { the e.printstacktrace (); +         } -     } $      $     /** - * Get Connected -      * @returnJedis the      */ -      Public StaticJedis getconn () {Wuyi         //Redis Objects theJedis Jedis =local.get (); -         if(jedis==NULL){ Wu             if(Jedispool = =NULL) {     - Initialpool ();  About             } $Jedis =Jedispool.getresource (); - Local.set (Jedis); -         } -         returnJedis;  A     } +      the     //Return Connection -      Public Static voidCloseconn () { $         //get from local thread theJedis Jedis =local.get (); the         if(jedis!=NULL){ the jedis.close (); the         } -Local.set (NULL); in     } the      the     //Close Pool About      Public Static voidClosepool () { the         if(jedispool!=NULL){ the jedispool.close (); the         } +     } -}

The last test method is tested using the above method.

Note::: May connect timeout failure, in fact, is a firewall problem, then open the firewall port, and then restart the firewall is OK.

Four: How Redis is persisted

In order to be able to query at high speed, Redis will almost all the data in memory, but the disadvantage is obvious, how to persist the data of Redis! There are two ways in which the official offers:

1:rdb: Generate a point-in-time snapshot of a dataset within a specified time interval, but if you don't have a power outage at the specified time interval, JJ!

2:AOF: Logs each step of the write instruction, and restores the database by executing these commands when the server starts. But the volume is bigger, the speed is very slow.

3: Generally two kinds of joint use, in fact, generally in the redis.conf has been configured, but you want to change and no one can stop you ah!

V: Other Operations

1:redis actually can have 16 database, from 0 to 15 number, by default select No. 0, with the Seclect keyword selection

2: Database must have transactional operations

Open transaction: Multi

Rollback: Discard

Submitted by: EXEC

Review and finish the basic application of 7:redis database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.