A brief introduction to the use of Redis in Java

introduce

Redisis an open source (BSD licensed), in-memory data structure storage system that can be used as database, cache, and messaging middleware. It supports multiple types of data structures such as strings, hashes, lists, sets, sorted sets and range queries, bitmaps, hyperloglogs and geospatial ( geospatial) index radius query. Redis has built-in replication (replication), LUA scripting (Lua scripting), LRU driven events (LRU eviction), transactions (transactions) and different levels of disk persistence (persistence), and through Redis sentinel (Sentinel) and automatic partition (Cluster) ) to provide high availability (high availability).

Version

official version

The current official version supports Linuxsystems and Ubuntusystems. Official download address: http://redis.io/download
Since our development project is mainly Windows, we will not introduce the official version in detail here. If you are interested, you can check it on the official website.

Unofficial version (Windows version)

There is no official Windows version, but a Win64 version is Redisdeveloped and maintained by the Microsoft Open Tech group . - Microsoft Teams only provides the official 64-bit version, and the 32-bit version, you need to build it yourself from source . - msi file is available in Released version and can be installed as a Windows service

Redis

install service
  • Download Win64 zip file to a specified folder
  • Open a cmd window and use the cd command to switch the directory to the unzipped folder and runredis-server.exe redis.windows.conf
    • redis-server.exeStart the Redis service
    • redis.windows.confSome configurations of the Redis service, if not written, the default settings will be called
    • By default, the port number 6379can be modified by modifying the configuration file redis.windows-service.confor by CONFIG setcommand.
run the client
  • Open a cmd window and use the cd command to change the directory to the unzipped folder and runredis-cli.exe -h 127.0.0.1 -p 6379
    • redis-cli.exeStart the Redis client
    • -h 127.0.0.1Server IP address
    • -p 6379server port number

advantage

  1. Fast, because the data is stored in memory, similar to HashMap, the advantage of HashMap is that the time complexity of search and operation is O(1)
  2. Support rich data types, support string (string), hash (hash), list (list), set (collection) and zset (sorted set: ordered set).
  3. Transactions are supported, and operations are atomic. The so-called atomicity means that all changes to the data are either executed or not executed at all.
  4. Rich features, can be used for cache, message, set expiration time according to key, it will be automatically deleted after expiration

shortcoming

  1. The storage cost of redis is high (only using memory, a single machine, the amount of data stored is related to the memory size of the machine itself), so it cannot be used as a massive database. Although redis itself has a key expiration policy, it still needs to be estimated and saved in advance. If memory grows too fast, data needs to be deleted periodically.
  2. If a complete resynchronization is performed, the rdb file needs to be generated and transmitted, which will occupy the CPU of the host and consume the bandwidth of the existing network. However, in version 2.8 of redis, there is already a partial resynchronization function, but it is still possible to have a complete resynchronization. For example, a newly launched standby machine.
  3. It takes a long time to modify the configuration file, restart, and load the data from the hard disk into the memory. During this process, redis cannot provide services.

Suitable for application scenarios

Redis is a k/v in-memory database, which is suitable for small data storage and high real-time requirements. O overhead, and more importantly, it can greatly improve the speed, but it is not suitable for a complete database, and a complete database basically has a set of detailed solutions.

Java using Redis

Install

  1. Install Redis service
  2. Configure the Java runtime environment to ensure that Java can be used normally
  3. Install the Java Redis driverjedis.jar

connect to redis service

import redis.clients.jedis.Jedis;

public class RedisJava {
    public static void main(String[] args) {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //查看服务是否运行
        System.out.println("服务正在运行: "+jedis.ping());
    }
}

Accessing data of type String

import redis.clients.jedis.Jedis;

public class RedisStringJava {
    public static void main(String[] args) {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //设置 redis 字符串数据
        jedis.set("runoobkey", "www.runoob.com");
        // 获取存储的数据并输出
        System.out.println("redis 存储的字符串为: "+ jedis.get("runoobkey"));
    }
}

Compilation result:

连接成功
redis 存储的字符串为: www.runoob.com

Accessing data of type List

import java.util.List;
import redis.clients.jedis.Jedis;

public class RedisListJava {
    public static void main(String[] args) {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //存储数据到列表中
        jedis.lpush("site-list", "Runoob");
        jedis.lpush("site-list", "Google");
        jedis.lpush("site-list", "Taobao");
        // 获取存储的数据并输出
        List<String> list = jedis.lrange("site-list", 0 ,2);
        for(int i=0; i<list.size(); i++) {
            System.out.println("列表项为: "+list.get(i));
        }
    }
}

Compilation result:

连接成功
列表项为: Taobao
列表项为: Google
列表项为: Runoob

Accessed Keys

import java.util.Iterator;
import java.util.Set;
import redis.clients.jedis.Jedis;

public class RedisKeyJava {
    public static void main(String[] args) {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");

        // 获取数据并输出
        Set<String> keys = jedis.keys("*");
        Iterator<String> it=keys.iterator() ;   
        while(it.hasNext()){   
            String key = it.next();   
            System.out.println(key);   
        }
    }
}

Compilation result:

连接成功
runoobkey
site-list

Redis publish and subscribe

Redis publish-subscribe (pub/sub) is a message communication mode: sender (pub) sends messages and subscribers (sub) receive messages.

Subscribe to a channel

By SUBSCRIBEcommanding the client to subscribe to the specified channel, when this channel has messages pushed by other clients, the current client will receive it.
Example: Subscribe to the first and second channels

SUBSCRIBE first second

message push

By PUBLISHcommanding the client to push messages to the specified channel, the clients subscribed to this channel will receive a message of type message.
Example: Push the message "Hello" to the first channel

PUBLISH first "Hello"

unsubscribe channel

The specified channel can be presumed by UNSUBSCRIBEcommanding the client. If no channel is specified, i.e. a parameterless UNSUBSCRIBE call is performed, then all channels subscribed by the client using the SUBSCRIBEcommand will be unsubscribed. In this case, the command returns a message informing the client of all unsubscribed channels.
Example: Unsubscribe from second channel

UNSUBSCRIBE second

pattern matching

RedisThe Pub/Sub implementation supports pattern matching. Clients can subscribe to full-style patterns in order to receive messages from all channels that match a given pattern.
- Pattern matching subscribe command PSUBSCRIBE
- Pattern matching unsubscribe command UNPSUBSCRIBE
- Receive message as pmessage type

SUBSCRIBE first
PSUBSCRIBE f*
PSUBSCRIBE news.*

Note: A client may receive a message multiple times if it subscribes to multiple patterns that match the same published message.

JAVA implements Redis message push

  1. Create a channel listener class that inherits the Redis abstract class JedisPubSuband implements its abstract methods. Subscribing to a channel, unsubscribing, receiving a message and other states will call corresponding methods accordingly.
  2. Subscribe to a channel
public class TestSubscribe {  
      public static void main(String[] args) {  
          //连接本地的 Redis 服务
          Jedis jedis = new Jedis("localhost");
          System.out.println("连接成功");
          // 创建频道监听对象
          RedisMsgPubSubListener listener = new RedisMsgPubSubListener();
          // 订阅频道,绑定监听
          jedis.subscribe(listener, "redisChatTest");  
      }  
}  

Note: subscribeIt is a blocking method. It will block here until the channel is unsubscribed. The subsequent code will only be executed when the subscription is unsubscribed.

  1. send messages
Public class TestPublish {  
      public static void main(String[] args) {
          Jedis jedis = new Jedis("localhost");  
          jedis.publish("redisChatTest", "Hello");  
          Thread.sleep(5000);  
          jedis.publish("redisChatTest", "Redis");  
          Thread.sleep(5000);  
          jedis.publish("redisChatTest", "Message publish");  
      }  
}  
  1. unsubscribe channel
import redis.clients.jedis.JedisPubSub;  
public class RedisMsgPubSubListener extends JedisPubSub {
      ...
      @Override  
      public void onMessage(String channel, String message) {  
          System.out.println("channel:" + channel + "receives message :" + message);
          // 退订  
          this.unsubscribe();  
      }  
      ...
}

Reference:
http://www.redis.cn/documentation.html
http://blog.csdn.net/u013322876/article/details/53817757
http://blog.csdn.net/canot/article/details/51938955

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325794873&siteId=291194637