Redis actively pushes data to the page

For the data that is periodically refreshed and displayed on the page, it has always been a more "traditional" idea - that is, "the page requests the background through ajax, and the background responds and returns the data to the foreground for display, and so on...", and I have never There is no concept of "the server actively pushes data to the page".

Now you need to use the publish/subscribe of redis, the page "subscribes" to a channel, and the server "publishes" content on a channel. After the server is published, the client can display the just-published content in real time by subscribing.

Tell me about the solution I found. . I used tomcat's WebSocketServlet, but found that it has been deprecated ( abandoned ) , and it must rely on tomcat, and the logic of foreground subscription is difficult to express, so I can't; later I thought of using @ServerEndpoint of javax.websocket-api.jar , but still stuck. . Because it is also difficult to reflect the publish/subscribe function of redis.

Later, I was struggling with which solution to use. At this time, the example of socket.io+redis+node.js real-time chat made my eyes shine. .

 

Well, let me talk about my understanding of nodejs - Node is a Javascript runtime environment (runtime), which is the server of Js, just like tomcat or weblogic is the runtime server of java code. . After installing nodejs, the latest version has brought npm, and npm is used to install various clients that support nodejs extensions. For example, if you want to use redis, you must install the nodejs client of redis. After configuring nodejs with environment variables, use the following command to install redis:

npm install redis

After installation, it defaults to an additional redis folder in C:\Users\xxx\node_modules, but if the nodejs you installed is not in the C drive, it is best to copy the module you just installed to node_modules under your installation package Under contents. Once installed, you can use require('redis') in Js.

socket.io is connected between the browser and the http server of nodejs, and can be used to synchronize data between the two. Again, it also needs to be installed via the npm command.

 

The solution process is as follows:

Write pubsub.js as the server that subscribes to a channel on the front page (for testing, I wrote the channel to death: var c = 'testchannel'; ):

 

var server = require('http').createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(1379);
 
var redis = require('redis');
var redisclient = redis.createClient();
 
var sub = function(c) {
    var c = 'testchannel';
    redisclient.subscribe(c, function(e) {
        console.log('subscribe channel : ' + c);
    });
}
sub();
 
console.log('Server running at http://127.0.0.1:1379/');
 
var io = require('socket.io')(server);
io.on('connection', function(socket) {
    redisclient.on('message', function(error, msg) {
        console.log('connection');
        console.log(msg);
        socket.emit('msgReceived', msg);        
    });
})

 

 

Then, define the front page that displays subscription messages:

 

<html>
<head>
<script src="F:\nodejs\node_modules\socket.io\node_modules\socket.io-client\socket.io.js"></script>
<script src="jquery-1.7.2.min.js"></script>

</head>
<body>
	<div style="width:100px; height:200px; border:1px solid red" id="show"></div>
	</script>hello world <script type="text/javascript">
	var div = $("#show");
	console.log("hello");
        var socket = io('http://localhost:1379');
	socket.on('connection', function() {
		console.log('connection setup for socket.io') });
	socket.on('msgReceived', function(msg) {
		//alert(div.html());
		div.append(msg + "<br/>");
		//alert(msg);
		})
</script>
</body>
</html>

 The var socket = io('http://localhost:1379'); line in the page is the key, which corresponds to listen(1379) in pubsub.js  . Indicates that the port 1379 of the local Nodejs server, listen (1379) in pubsub.js is monitored.

 

Use any browser (I'm Google's here) to open the front page you just defined.



 The page has no content at this time, because pubsub.js has not been opened to initiate a subscription request.

OK, we start running pubsub.js to initiate the request



 

Next, use redis to issue a request:

Open the redis service:



 

 Open another client and publish a message to testchannel:



 

Run pubsub.js: node pubsub.js

can be seen:



 

Open a redis client to see the subscription content:



 

The point is, the page can also display the content of the subscription:



 

In the same way, if you write the code published to the channel testchannel in java, the front page can also be displayed.

And if you open another browser (such as Sogou), you can also see the real-time subscribed news:



 This shows that the effect of redis actively pushing data to the page and pushing it in real time has been achieved.

Summary: nodejs is the running server of pubsub.js for page subscription, and socket.io is a function similar to websocket. It realizes the bridge between nodejs and browser and is the key for redis to push data to the page. Also note that nodejs uses the two modules redis and socket.io, you must first install the extension with the npm command. Pay attention to the model of the redis publish and subscribe idea in real-time push - the front page subscribes to the news of a certain channel, and the published words are published by redis.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327004249&siteId=291194637