JavaWeb14_Redis learning

Use catalog better!

Redis learning

Redis

  • Redis Chinese network Tutorial: https: //www.redis.net.cn/tutorial/3501.html

concept

  • redis is a high performance NOSQL series of non-relational databases

What is NOSQL?

  • NoSQL (NoSQL = Not Only SQL) , which means "not only SQL", is a new database concept, refers to non-relational database .
  • With the rise of the Internet web2.0 websites, traditional relational databases in dealing with web2.0 site, especially ultra- large-scale and high concurrent SNS type of web2.0 pure dynamic site has appeared to be inadequate, exposed a lot of problems difficult to overcome rather than relational databases due to its own characteristics has been very rapid development. Produced NoSQL database is to solve large-scale data collection of multiple data types of challenges brought about , especially large data application problems.
  • Compare NOSQL and relational databases
    • advantage:
      • Cost: nosql database is simple and easy to deploy, basically open source software, do not need to spend a lot like using oracle as the cost of purchase and use, compared to relational databases cheap.
      • Query speed: nosql into the database stores data in cache, relational database stores data in the hard disk, far less than the natural query speed nosql database.
      • Format to store data: nosql storage format is key, value form, the form of documents, pictures, forms, etc., can be stored in various formats as well as the basis of the type of objects or collections, etc., and the database only supports basic types.
      • Scalability: relational database query mechanism similar multi-table join such restrictions lead to expansion very difficult.
    • Disadvantages:
      • Maintenance tools and information is limited, because nosql belongs to new technologies, and not 10 years of relational database technology in the same category.
      • Sql does not provide support for, if not to support industry standards such as sql, will have some users to learn and use cost.
      • It does not provide a relational database processing of the transaction.
  • The advantages of non-relational databases
    • NOSQL performance is based on the key, it is conceivable to the corresponding values ​​and the relationship between the primary key in the table, and does not require the parsed SQL layer, the performance is very high.
    • Scalability is also based on key-value pair because no coupling between the data, it is very easy to expand horizontally.
  • The advantages of relational database
    • Complex queries can use SQL statements to do very complex data queries between a table and a convenient in multiple tables.
    • Transaction support enables data access requirements for the safety of high performance can be achieved. For these two types of databases, the other advantage is their weakness, and vice versa.
  • Relational databases and non-relational databases:Here Insert Picture Description
  • to sum up
    • Relational databases and NoSQL databases are not opposing but complementary relationship that the use of relational databases under normal circumstances, the use of NoSQL NoSQL database for use when,
    • Let NoSQL database for lack of relational database compensate.
    • Will generally be in a relational database, a relational database to store data backup data is stored in a database nosql

Mainstream products NOSQL

  • Key (Key-Value) stored in the database
    • Related Products: Tokyo Cabinet / Tyrant, Redis, Voldemort, Berkeley DB
    • Typical applications: high access content caching, mainly used for processing large amounts of data load.
    • Data model: a series of key-value pairs
    • Advantage: Quick Query
    • Weaknesses: The lack of structured data storage
  • Column-store database
    • Related Products: Cassandra, HBase, Riak
    • Typical applications: distributed file system
    • Data Model: a column storage clusters, with the presence of the same row of data
    • Advantages: Fast search speed, scalability, easier to distributed expansion
    • Disadvantages: relatively limited functions
  • Document database
    • Related Products: CouchDB, MongoDB
    • Typical applications: Web Application (similar to the Key-Value, Value is structured)
    • Data model: a series of key-value pairs
    • Advantages: data structure is not strictly required
    • Disadvantages: query performance is not high, and the lack of a unified query syntax
  • Graphics (Graph) database
    • Relational database: Neo4J, InfoGrid, Infinite Graph
    • Typical applications: social networking
    • Data Model: Structure FIG.
    • Advantages: FIG structurally related algorithms.
    • Disadvantages: need to do in order to calculate the outcome of the whole map, not easy to do a distributed cluster program.

What is Redis

  • Redis key to provide high performance with an open source development language for C (key-value) database, the official test data, 50 100 000 concurrent execution requests, read speed is 110,000 times / s, write speed is 81000 times / s, and by providing a plurality of key Redis data types to accommodate the needs of different scenarios stored

  • So far Redis support of key data types are as follows:

    • String type string
    • String type string
    • List type list
    • Collection types set
    • Indexed collections sortedset
  • redis application scenarios

    • Cache (data queries, short connections, news content, goods, content, etc.)
    • Online chat room buddy list
    • Task queue. (Spike, buy, 12306, etc.)
    • Application Ranking
    • Website statistics
    • Processing data has expired (accurate to milliseconds)
    • Distributed cluster architecture separate session
  • Note :

    • Redis use to cache some data changes do not occur frequently.
      • Once the data in the database changes, we need to update the cache.
      • Table additions and deletions to perform database-related operations, you need to redis cache data, the stored again
      • In the method of CRUD service corresponding to the data deleted redis.

Download and install

  • Official website: https: //redis.io
  • Chinese net: http: //www.redis.net.cn/
  • Decompression can be used directly:
    • redis.windows.conf: Profile
    • redis-cli.exe: redis client
    • redis-server.exe: redis server

Command Operation

  • redis data structure

    • redis is stored: data key, value format, wherein the key is a string, value five different data structures
      • value data structure
        • String type string
        • Hash type hash: map format
        • List type list: linkedlist format. Support repeating elements
        • Collection types set: do not allow duplicate elements
        • Type ordered set sortedset: not allow duplicate elements, and sequential elements
  • Icon:Here Insert Picture Description

  • String type string

    • Storage: set key value

      127.0.0.1:6379> set username zhangsan
      OK
      
    • Get: get key

      127.0.0.1:6379> get username
      "zhangsan"
      
    • Delete: del key

      127.0.0.1:6379> del age
      (integer) 1
      
  • Type hash hash

    • Storage: hset key field value

      127.0.0.1:6379> hset myhash username lisi
      (integer) 1
      127.0.0.1:6379> hset myhash password 123
      (integer) 1
      
    • Obtain:

      • hget key field: 获取指定的field对应的值

        127.0.0.1:6379> hget myhash username
        "lisi"
        
      • hgetall key:获取所有的field和value

        127.0.0.1:6379> hgetall myhash
        1) "username"
        2) "lisi"
        3) "password"
        4) "123"
        
    • 删除: hdel key field

      127.0.0.1:6379> hdel myhash username
      (integer) 1
      
  • 列表类型 list

    • 可以添加一个元素到列表的头部(左边)或者尾部(右边)

    • 添加:

      • lpush key value: 将元素加入列表左表

      • rpush key value:将元素加入列表右边

        127.0.0.1:6379> lpush myList a
        (integer) 1
        127.0.0.1:6379> lpush myList b
        (integer) 2
        127.0.0.1:6379> rpush myList c
        (integer) 3
        
    • 获取:lrange key start end :范围获取

      127.0.0.1:6379> lrange myList 0 -1
      1) "b"
      2) "a"
      3) "c"
      
    • 删除:

    • lpop key: 删除列表最左边的元素,并将元素返回

    • rpop key: 删除列表最右边的元素,并将元素返回

  • 集合类型 set:不允许重复元素

    • 存储:sadd key value

      127.0.0.1:6379> sadd myset a
      (integer) 1
      127.0.0.1:6379> sadd myset a
      (integer) 0
      
    • 获取:smembers key:获取set集合中所有元素

      127.0.0.1:6379> smembers myset
      1) "a"
      
    • 删除:srem key value:删除set集合中的某个元素

      127.0.0.1:6379> srem myset a
      (integer) 1
      
  • 有序集合类型 sortedset

    • 不允许重复元素,且元素有顺序.每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。

    • 存储:zadd key score value

      127.0.0.1:6379> zadd mysort 60 zhangsan
      (integer) 1
      127.0.0.1:6379> zadd mysort 50 lisi
      (integer) 1
      127.0.0.1:6379> zadd mysort 80 wangwu
      (integer) 1
      
    • 获取:zrange key start end [withscores]

      127.0.0.1:6379> zrange mysort 0 -1
      1) "lisi"
      2) "zhangsan"
      3) "wangwu"
      
      127.0.0.1:6379> zrange mysort 0 -1 withscores
      1) "zhangsan"
      2) "60"
      3) "wangwu"
      4) "80"
      5) "lisi"
      6) "500"
      
    • 删除:zrem key value

      127.0.0.1:6379> zrem mysort lisi
      (integer) 1
      
  • 通用命令

    • keys * : 查询所有的键
    • type key : 获取键对应的value的类型
    • del key:删除指定的key value

持久化

  • redis是一个内存数据库,当redis服务器重启,获取电脑重启,数据会丢失,我们可以将redis内存中的数据持久化保存到硬盘的文件中。

  • redis持久化机制:

    • RDB:默认方式,不需要进行配置,默认就使用这种机制

      • 在一定的间隔时间中,检测key的变化情况,然后持久化数据

      • 编辑redis.windwos.conf文件

        #   after 900 sec (15 min) if at least 1 key changed
        save 900 1
        #   after 300 sec (5 min) if at least 10 keys changed
        save 300 10
        #   after 60 sec if at least 10000 keys changed
        save 60 10000
        
      • 重新启动redis服务器,并指定配置文件名称

        D:\JavaWeb\redis\windows-64\redis-2.8.9>redis-server.exe redis.windows.conf

    • AOF:日志记录的方式,可以记录每一条命令的操作。可以每一次命令操作后,持久化数据

      • 编辑redis.windwos.conf文件

        appendonly no(关闭aof) --> appendonly yes (开启aof)
        
        # appendfsync always : 每一次操作都进行持久化
        appendfsync everysec : 每隔一秒进行一次持久化
        # appendfsync no	 : 不进行持久化
        

Java客户端 Jedis

  • Jedis: 一款java操作redis数据库的工具.

  • 使用步骤:

    • 下载jedis的jar包

    • 使用

      //1. 获取连接
      Jedis jedis = new Jedis("localhost",6379);
      //2. 操作
      jedis.set("username","zhangsan");
      //3. 关闭连接
      jedis.close();
      
  • Jedis operation of various data structures in redis

    • String type string

      • set

      • get

        //1. 获取连接
        Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口
        //2. 操作
        //存储
        jedis.set("username","zhangsan");
        //获取
        String username = jedis.get("username");
        System.out.println(username);
        
        //可以使用setex()方法存储可以指定过期时间的 key value
        jedis.setex("activecode",20,"hehe");//将activecode:hehe键值对存入redis,并且20秒后自动删除该键值对
        
        //3. 关闭连接
        jedis.close();
        
    • Hash type hash: map format

      • hset

      • hget

      • hgetAll

        //1. 获取连接
        Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口
        //2. 操作
        // 存储hash
        jedis.hset("user","name","lisi");
        jedis.hset("user","age","23");
        jedis.hset("user","gender","female");
        
        // 获取hash
        String name = jedis.hget("user", "name");
        System.out.println(name);
        // 获取hash的所有map中的数据
        Map<String, String> user = jedis.hgetAll("user");
        
        // keyset
        Set<String> keySet = user.keySet();
        for (String key : keySet) {
        //获取value
        String value = user.get(key);
        System.out.println(key + ":" + value);
        }
        
        //3. 关闭连接
        jedis.close();
        
    • List type list: linkedlist format. Support repeating elements

      • Lpus / Rpus

      • lpop / rpop

      • lrange start end: acquiring range

        //1. 获取连接
        Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口
        //2. 操作
        // list 存储
        jedis.lpush("mylist","a","b","c");//从左边存
        jedis.rpush("mylist","a","b","c");//从右边存
        
        // list 范围获取
        List<String> mylist = jedis.lrange("mylist", 0, -1);
        System.out.println(mylist);
        
        // list 弹出
        String element1 = jedis.lpop("mylist");//c
        System.out.println(element1);
        
        String element2 = jedis.rpop("mylist");//c
        System.out.println(element2);
        
        // list 范围获取
        List<String> mylist2 = jedis.lrange("mylist", 0, -1);
        System.out.println(mylist2);
        
        //3. 关闭连接
        jedis.close();
        
    • Collection types set: do not allow duplicate elements

      • sadd

      • smembers: Get all the elements

        //1. 获取连接
        Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口
        //2. 操作
        // set 存储
        jedis.sadd("myset","java","php","c++");
        
        // set 获取
        Set<String> myset = jedis.smembers("myset");
        System.out.println(myset);
        
        //3. 关闭连接
        jedis.close();
        5) 有序集合类型 sortedset:不允许重复元素,且元素有顺序
        zadd
        zrange
        
        //1. 获取连接
        Jedis jedis = new Jedis();//如果使用空参构造,默认值 "localhost",6379端口
        //2. 操作
        // sortedset 存储
        jedis.zadd("mysortedset",3,"亚瑟");
        jedis.zadd("mysortedset",30,"后裔");
        jedis.zadd("mysortedset",55,"孙悟空");
        
        // sortedset 获取
        Set<String> mysortedset = jedis.zrange("mysortedset", 0, -1);
        
        System.out.println(mysortedset);
        //3. 关闭连接
        jedis.close();
        
  • jedis connection pool: JedisPool

    • use:

      • Create a connection pool object JedisPool

      • Call the method getResource () method to get connected Jedis

        				//0.创建一个配置对象
        		        JedisPoolConfig config = new JedisPoolConfig();
        		        config.setMaxTotal(50);
        		        config.setMaxIdle(10);
        		
        		        //1.创建Jedis连接池对象
        		        JedisPool jedisPool = new JedisPool(config,"localhost",6379);
        		
        		        //2.获取连接
        		        Jedis jedis = jedisPool.getResource();
        		        //3. 使用
        		        jedis.set("hehe","heihei");
        		        		        //4. 关闭 归还到连接池中
        		        jedis.close();
        		
        		* 连接池工具类
        			public class JedisPoolUtils {
        
        			    private static JedisPool jedisPool;
        			
        			    static{
        			        //读取配置文件
        			        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        			        //创建Properties对象
        			        Properties pro = new Properties();
        			        //关联文件
        			        try {
        			            pro.load(is);
        			        } catch (IOException e) {
        			            e.printStackTrace();
        			        }
        			        //获取数据,设置到JedisPoolConfig中
        			        JedisPoolConfig config = new JedisPoolConfig();
        			        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        			        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
        			
        			        //初始化JedisPool
        			        jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
        			        			    }
        			        			    			    /**
        			     * 获取连接方法
        			     */
        			    public static Jedis getJedis(){
        			        return jedisPool.getResource();
        			    }
        			}
        		        
        
Published 53 original articles · won praise 11 · views 9366

Guess you like

Origin blog.csdn.net/SeafyLiang/article/details/104565281