Skip to content

Commit bf5b304

Browse files
egoebelbeckermaibin
authored andcommitted
BAEL-1486 - sample code for JGroups. Fixed a typo in InfluxDB. (eugenp#3578)
1 parent 8b76303 commit bf5b304

7 files changed

Lines changed: 323 additions & 3 deletions

File tree

‎influxdb/README.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
### Relevant Article:
44
- [Introduction to using InfluxDB with Java](http://www.baeldung.com/using-influxdb-with-java/)
5-
- [Using InfluxDB with Java](http://www.baeldung.com/java-influxdb)
65

76
### Overview
87
This Maven project contains the Java code for the article linked above.

‎influxdb/src/test/java/com/baeldung/influxdb/InfluxDBConnectionLiveTest.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import org.influxdb.impl.InfluxDBResultMapper;
99
import org.junit.Test;
1010

11-
import java.io.IOException;
1211
import java.util.List;
1312
import java.util.concurrent.TimeUnit;
1413

@@ -103,7 +102,7 @@ public void whenPointsWrittenPointsExists() throws Exception {
103102
// another brief pause.
104103
Thread.sleep(10);
105104

106-
List<MemoryPoint> memoryPointList = getPoints(connection, "Select * from memory", "baeldung");
105+
List<com.baeldung.influxdb.MemoryPoint> memoryPointList = getPoints(connection, "Select * from memory", "baeldung");
107106

108107
assertEquals(10, memoryPointList.size());
109108

‎jgroups/README.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
## Reliable Messaging with JGroups Tutorial Project
2+
3+
### Relevant Article:
4+
- [Reliable Messaging with JGroups](http://www.baeldung.com/reliable-messaging-with-jgroups/)
5+
6+
### Overview
7+
This Maven project contains the Java code for the article linked above.
8+
9+
### Package Organization
10+
Java classes for the intro tutorial are in the org.baeldung.jgroups package.
11+
12+
13+
### Running the tests
14+
15+
```

‎jgroups/pom.xml‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<artifactId>jgroups</artifactId>
6+
<version>0.1-SNAPSHOT</version>
7+
<packaging>jar</packaging>
8+
<name>jgroups</name>
9+
<description>Reliable Messaging with JGroups Tutorial</description>
10+
11+
<parent>
12+
<groupId>com.baeldung</groupId>
13+
<artifactId>parent-modules</artifactId>
14+
<version>1.0.0-SNAPSHOT</version>
15+
</parent>
16+
17+
<dependencies>
18+
<dependency>
19+
<groupId>org.jgroups</groupId>
20+
<artifactId>jgroups</artifactId>
21+
<version>4.0.10.Final</version>
22+
</dependency>
23+
24+
<dependency>
25+
<groupId>commons-cli</groupId>
26+
<artifactId>commons-cli</artifactId>
27+
<version>1.4</version>
28+
</dependency>
29+
</dependencies>
30+
31+
<properties>
32+
<java.version>1.8</java.version>
33+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
34+
</properties>
35+
36+
</project>
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
package com.baeldung.jgroups;
2+
3+
import org.apache.commons.cli.*;
4+
import org.jgroups.*;
5+
import org.jgroups.util.Util;
6+
7+
import java.io.*;
8+
import java.util.List;
9+
import java.util.Optional;
10+
11+
public class JGroupsMessenger extends ReceiverAdapter {
12+
13+
private JChannel channel;
14+
private String userName;
15+
private String clusterName;
16+
private View lastView;
17+
private boolean running = true;
18+
19+
// Our shared state
20+
private Integer messageCount = 0;
21+
22+
/**
23+
* Connect to a JGroups cluster using command line options
24+
* @param args command line arguments
25+
* @throws Exception
26+
*/
27+
private void start(String[] args) throws Exception {
28+
processCommandline(args);
29+
30+
// Create the channel
31+
// This file could be moved, or made a command line option.
32+
channel = new JChannel("src/main/resources/udp.xml");
33+
34+
// Set a name
35+
channel.name(userName);
36+
37+
// Register for callbacks
38+
channel.setReceiver(this);
39+
40+
// Ignore our messages
41+
channel.setDiscardOwnMessages(true);
42+
43+
// Connect
44+
channel.connect(clusterName);
45+
46+
// Start state transfer
47+
channel.getState(null, 0);
48+
49+
// Do the things
50+
processInput();
51+
52+
// Clean up
53+
channel.close();
54+
55+
}
56+
57+
/**
58+
* Quick and dirty implementaton of commons cli for command line args
59+
* @param args the command line args
60+
* @throws ParseException
61+
*/
62+
private void processCommandline(String[] args) throws ParseException {
63+
64+
// Options, parser, friendly help
65+
Options options = new Options();
66+
CommandLineParser parser = new DefaultParser();
67+
HelpFormatter formatter = new HelpFormatter();
68+
69+
options.addOption("u", "user", true, "User name")
70+
.addOption("c", "cluster", true, "Cluster name");
71+
72+
CommandLine line = parser.parse(options, args);
73+
74+
if (line.hasOption("user")) {
75+
userName = line.getOptionValue("user");
76+
} else {
77+
formatter.printHelp("JGroupsMessenger: need a user name.\n", options);
78+
System.exit(-1);
79+
}
80+
81+
if (line.hasOption("cluster")) {
82+
clusterName = line.getOptionValue("cluster");
83+
} else {
84+
formatter.printHelp("JGroupsMessenger: need a cluster name.\n", options);
85+
System.exit(-1);
86+
}
87+
}
88+
89+
// Start it up
90+
public static void main(String[] args) throws Exception {
91+
new JGroupsMessenger().start(args);
92+
}
93+
94+
95+
@Override
96+
public void viewAccepted(View newView) {
97+
98+
// Save view if this is the first
99+
if (lastView == null) {
100+
System.out.println("Received initial view:");
101+
newView.forEach(System.out::println);
102+
} else {
103+
104+
// Compare to last view
105+
System.out.println("Received new view.");
106+
107+
List<Address> newMembers = View.newMembers(lastView, newView);
108+
if (newMembers.size() > 0) {
109+
System.out.println("New members: ");
110+
newMembers.forEach(System.out::println);
111+
}
112+
113+
List<Address> exMembers = View.leftMembers(lastView, newView);
114+
if (exMembers.size() > 0) {
115+
System.out.println("Exited members:");
116+
exMembers.forEach(System.out::println);
117+
}
118+
}
119+
lastView = newView;
120+
}
121+
122+
/**
123+
* Loop on console input until we see 'x' to exit
124+
*/
125+
private void processInput() {
126+
127+
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
128+
while (running) {
129+
try {
130+
131+
// Get a destination, <enter> means broadcast
132+
Address destination = null;
133+
System.out.print("Enter a destination: ");
134+
System.out.flush();
135+
String destinationName = in.readLine().toLowerCase();
136+
137+
if (destinationName.equals("x")) {
138+
running = false;
139+
continue;
140+
} else if (!destinationName.isEmpty()) {
141+
Optional<Address> optDestination = getAddress(destinationName);
142+
if (optDestination.isPresent()) {
143+
destination = optDestination.get();
144+
} else {
145+
System.out.println("Destination not found, try again.");
146+
continue;
147+
}
148+
}
149+
150+
// Accept a string to send
151+
System.out.print("Enter a message: ");
152+
System.out.flush();
153+
String line = in.readLine().toLowerCase();
154+
sendMessage(destination, line);
155+
} catch (IOException ioe) {
156+
running = false;
157+
}
158+
}
159+
System.out.println("Exiting.");
160+
}
161+
162+
/**
163+
* Send message from here
164+
* @param destination the destination
165+
* @param messageString the message
166+
*/
167+
private void sendMessage(Address destination, String messageString) {
168+
try {
169+
System.out.println("Sending " + messageString + " to " + destination);
170+
Message message = new Message(destination, messageString);
171+
channel.send(message);
172+
} catch (Exception exception) {
173+
System.err.println("Exception sending message: " + exception.getMessage());
174+
running = false;
175+
}
176+
}
177+
178+
@Override
179+
public void receive(Message message) {
180+
// Print source and dest with message
181+
String line = "Message received from: " + message.getSrc() + " to: " + message.getDest() + " -> " + message.getObject();
182+
183+
// Only track the count of broadcast messages
184+
// Tracking direct message would make for a pointless state
185+
if (message.getDest() == null) {
186+
messageCount++;
187+
System.out.println("Message count: " + messageCount);
188+
}
189+
190+
System.out.println(line);
191+
}
192+
193+
@Override
194+
public void getState(OutputStream output) throws Exception {
195+
// Serialize into the stream
196+
Util.objectToStream(messageCount, new DataOutputStream(output));
197+
}
198+
199+
@Override
200+
public void setState(InputStream input) {
201+
202+
// NOTE: since we know that incrementing the count and transferring the state
203+
// is done inside the JChannel's thread, we don't have to worry about synchronizing
204+
// messageCount. For production code it should be synchronized!
205+
try {
206+
// Deserialize
207+
messageCount = Util.objectFromStream(new DataInputStream(input));
208+
} catch (Exception e) {
209+
System.out.println("Error deserialing state!");
210+
}
211+
System.out.println(messageCount + " is the current messagecount.");
212+
}
213+
214+
215+
private Optional<Address> getAddress(String name) {
216+
View view = channel.view();
217+
return view.getMembers().stream().filter(address -> name.equals(address.toString())).findFirst();
218+
}
219+
220+
}
221+
222+

‎jgroups/src/main/resources/udp.xml‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<config xmlns="urn:org:jgroups"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="urn:org:jgroups http://www.jgroups.org/schema/jgroups.xsd">
4+
<UDP
5+
mcast_port="${jgroups.udp.mcast_port:45588}"
6+
ip_ttl="4"
7+
tos="8"
8+
ucast_recv_buf_size="5M"
9+
ucast_send_buf_size="5M"
10+
mcast_recv_buf_size="5M"
11+
mcast_send_buf_size="5M"
12+
max_bundle_size="64K"
13+
enable_diagnostics="true"
14+
thread_naming_pattern="cl"
15+
16+
thread_pool.min_threads="0"
17+
thread_pool.max_threads="20"
18+
thread_pool.keep_alive_time="30000"/>
19+
20+
<PING />
21+
<MERGE3 max_interval="30000"
22+
min_interval="10000"/>
23+
<FD_SOCK/>
24+
<FD_ALL/>
25+
<VERIFY_SUSPECT timeout="1500" />
26+
<BARRIER />
27+
<pbcast.NAKACK2 xmit_interval="500"
28+
xmit_table_num_rows="100"
29+
xmit_table_msgs_per_row="2000"
30+
xmit_table_max_compaction_time="30000"
31+
use_mcast_xmit="false"
32+
discard_delivered_msgs="true"/>
33+
<UNICAST3 xmit_interval="500"
34+
xmit_table_num_rows="100"
35+
xmit_table_msgs_per_row="2000"
36+
xmit_table_max_compaction_time="60000"
37+
conn_expiry_timeout="0"/>
38+
<pbcast.STABLE desired_avg_gossip="50000"
39+
max_bytes="4M"/>
40+
<pbcast.GMS print_local_addr="true" join_timeout="2000"/>
41+
<UFC max_credits="2M"
42+
min_threshold="0.4"/>
43+
<MFC max_credits="2M"
44+
min_threshold="0.4"/>
45+
<FRAG2 frag_size="60K" />
46+
<RSVP resend_interval="2000" timeout="10000"/>
47+
<pbcast.STATE_TRANSFER />
48+
</config>

‎pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
<module>javax-servlets</module>
9494
<module>javaxval</module>
9595
<module>jaxb</module>
96+
<module>jgroups</module>
9697
<module>jee-7</module>
9798
<!-- <module>jhipster/jhipster-monolithic</module> -->
9899
<module>jjwt</module>

0 commit comments

Comments
 (0)