Redis publish and subscribe

Source: Internet
Author: User

Start the subscription and publish Client

On the subscription Client

Redis 127.0.0.1: 6379> PSUBSCRIBE share

Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "share"

3) (integer) 1

Indicates that the client subscribes to the share channel

1 indicates that the number of connected subscription channels in the client is 1.

On the publish client, publish a message for this channel

Redis 127.0.0.1: 6379> publish share "share"
(Integer) 1

1 indicates that one connection receives the message.

Subscription client display:

1) "pmessage" // Message Type
2) "share" // The Name Of The channel I subscribed
3) "share" // The Name Of The channel I receive
4) "share" // message content

Ps: The java Implementation subscription code is attached:

  1. Public Static VoidMain (String [] args ){
  2. String cmd ="Subscribe share \ r \ n";
  3. SocketChannel client =Null;
  4. Try{
  5. SocketAddress address =NewInetSocketAddress ("Localhost",6379);
  6. Client = SocketChannel. open (address );
  7. Client. configureBlocking (False);// Set to asynchronous
  8. ByteBuffer buffer = ByteBuffer. allocate (100);
  9. Buffer. put (cmd. getBytes ());
  10. Buffer. clear ();
  11. Client. write (buffer );
  12. System. out. println ("Send data :"+NewString (buffer. array ()));
  13. While(True){
  14. Buffer. flip ();
  15. IntI = client. read (buffer );
  16. If(I>0){
  17. Byte[] B = buffer. array ();
  18. System. out. println ("Receive data :"+NewString (B ));
  19. Break;
  20. }
  21. }
  22. }Catch(Exception e ){
  23. Try{
  24. Client. close ();
  25. }Catch(IOException e1 ){
  26. E1.printStackTrace ();
  27. }
  28. E. printStackTrace ();
  29. }
  30. }

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.