Simple chat room implementation based on subscription/release mode (Java+redis)

Source: Internet
Author: User
Tags redis

This blog post mainly introduces the implementation of the simple chat room from the following two parts:
1. Introduction to Redis Publish subscription mode
2.java Code Implementation Subscription Publishing mode

One, Redis Publish subscription mode
Redis subscriptions are divided into subscription channels and subscription modes
1. Subscribe to the Channel
Open a client 1 and subscribe to the movie Live channel:
127.0.0.1:6379> Subscribe "Movie::live::room"
Publish a message on the movie Live channel
127.0.0.1:6379> publish Movie::live::room "Does someone like Snow White?"
After the message is published, the client 1 of the subscription message receives the published information. If we want to subscribe to multiple channels, we can use subscription mode.

2. Subscription mode
Reopen a client 2 and subscribe to the movie mode:
127.0.0.1:6379> psubscribe "movie*"
At this point, the message is republished on the movie Live channel, and client 1 and client 2 will receive the published message.
If you post a message B on the movie History Channel,
127.0.0.1:6379> publish Movie::history::room "Does someone like Snow White?"
Only client 2 will receive the message at this time.
Subscription mode support *,? , [] Three modes
* Match all the characters that follow
? Match one character
[] match the characters in brackets H[eo]llo match Hello and Hollo

Second, the Java Code Implementation subscription Publishing mode
Next, use Jedis to implement a simple chat room
We use Redis as a service forwarding, so there is no service-side code, just write the client can be:
Define the client, the function is relatively simple, enter the room hint, leave the room prompt, speak in the room:

Package redis.publishandsubscribe;

Import Java.util.Scanner;

Import Redis. Redisutil;

public class Client {
    private String name;
    Private Chatsubscribe Roomsublisterner;

    Public Client () {
        Roomsublisterner = new Chatsubscribe ();
    }

    public void SetName (String name) {
        this.name =name;
    }
    Public String GetName () {return
        name;
    }
    * * Enter room
    /public void Subscribe (final string[] room) {
        Chatsubscribe roomsub = Roomsublisterner;
        Roomsub.setclientname (name);
        Roomsub.setroom (room);
        Redisutil.subscribe (room, roomsub);
    }
    /* Exit Room */public
    void Unsubscribe (final string[] room) {
        roomsublisterner.unsubscribe (room);
    }
    /* speak */public
    void Say (final String room,string message) {
        redisutil.publish (room, name+ "say:" +message);
    }
}

In the code above, there is a Chatsubscribe class, the class for the Chat room action listener class, in which we define only the subscription channel, unsubscribe channel, receive message method:

Package redis.publishandsubscribe; Import Redis.
Redisutil;

Import Redis.clients.jedis.JedisPubSub;
    public class Chatsubscribe extends jedispubsub{/* Member name */private String clientname;

    * * Room name/private string[] room;
    Public String Getclientname () {return clientname;
    } public void Setclientname (String clientname) {this.clientname = ClientName;
    String[] Getroom () {return room;
    } public void Setroom (string[] room) {this.room = room; @Override public void Onunsubscribe (String channel, int subscribedchannels) {//do Nothing} @ Override public void Onsubscribe (String channel, int subscribedchannels) {redisutil.publish (Channel,clientna
    Me+ "Enter the room"); @Override public void Onpunsubscribe (String pattern, int subscribedchannels) {} @Override Public void Onpsubscribe (String pattern, int subscribedchannels) {} @Override Public void Onpmessage (string pattern, string channel, String message) {} @Override public void OnMessage (STR
    ing channel, String message) {SYSTEM.OUT.PRINTLN ("received messages from the +channel+ Room:" +message); @Override public void Unsubscribe (string ... channels) {for (string c:channels) REDISUTIL.P
        Ublish (c, clientname+ "leave the room");
    Super.unsubscribe (Channels);
 }
}

Next Redis the generic class:

Package Redis;
Import Redis.clients.jedis.Jedis;
Import Redis.clients.jedis.JedisPool;
Import Redis.clients.jedis.JedisPoolConfig;

Import Redis.clients.jedis.JedisPubSub;

    public class Redisutil {private static Jedispool jedispool;
        Private Redisutil () {} static {Jedispoolconfig poolconfig = new Jedispoolconfig ();
        Poolconfig.setmaxidle (5);
        Poolconfig.setminidle (1);
        Poolconfig.settestonborrow (TRUE);
        Poolconfig.setnumtestsperevictionrun (10);
        Poolconfig.settimebetweenevictionrunsmillis (60000);

        Poolconfig.setmaxwaitmillis (10000);
    Jedispool = new Jedispool (poolconfig, "127.0.0.1", 6379);
    private static void Returnresource (Jedis Jedis) {jedispool.returnresource (Jedis);
        /* Publish message/* public static void publish (String channel, String message) {Jedis Jedis = null;
            try{Jedis = Jedispool.getresource ();
        Jedis.publish (channel, message); }cAtch (Exception e) {System.out.println (e);
        }finally{Returnresource (Jedis);
    }
    };
        /* Subscribe to room/public static void subscribe (string[] room, jedispubsub pubSub) {Jedis = null;
            try{Jedis = Jedispool.getresource ();
        Jedis.subscribe (PubSub, room);
        }catch (Exception e) {System.out.println (e);
        }finally{Returnresource (Jedis);
 }
    }
}

Finally, the main function starts the client:

    public static void Main (string[] args) throws Interruptedexception {
        Final client client = new client ();
        Client.setname ("Mark");
        Final string[] rooms = {"Movie::live::room"};
        New Thread (New Runnable () {
            @Override public
            void Run () {
//              string[] rooms = {"Peter::live::room", "Bob :: Live::room "};
                Client.subscribe (rooms);
            }
        ). Start ();
        Thread.Sleep (3000);
        while (true) {
            System.out.print ("Say Something:");
            Scanner Scanner = new Scanner (system.in);
            String message = Scanner.nextline (); 
            if ("Quit". Equals (Message)) {break
                ;
            } else{
                Client.say (rooms[0], message);
                System.out.println ();
            }
        String[] unsubroom ={"Movie::live::room"}; 
        Client.unsubscribe (unsubroom);
    }

To do this, a simple chat room is written.

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.