when i try to send a async message by rocketMQ,exception :
org.apache.rocketmq.remoting.exception.RemotingConnectException: connect to [192.168.2.115:9876] failed
pom:
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.9.3</version>
</dependency>
code:
public static void main(String[] args) throws Exception {
// 实例化消费生产者
DefaultMQProducer producer = new DefaultMQProducer("async_group");
// 指定NameServer地址,可以是多个,分号隔开
// producer.setNamesrvAddr("localhost:9876;localhost:9877");
producer.setNamesrvAddr("192.168.2.115:9876");
// 启动producer
producer.start();
// 创建消息对象,指定主题topic,Tag和消息体
Message message = new Message("async_basic", "async_tag", ("i am async body,num:").getBytes());
producer.send(message, new SendCallback() {
#Override
public void onSuccess(SendResult sendResult) {
System.out.println("发送状态:" + sendResult);
}
#Override
public void onException(Throwable throwable) {
throwable.printStackTrace();
}
});
// 关闭
producer.shutdown();
}
i think it is the SendCallback,because sync message has no problem,and this code si right
public static void main(String[] args) throws Exception {
// 实例化消费生产者
DefaultMQProducer producer = new DefaultMQProducer("async_group");
// 指定NameServer地址,可以是多个,分号隔开
// producer.setNamesrvAddr("localhost:9876;localhost:9877");
producer.setNamesrvAddr("192.168.2.115:9876");
// 启动producer
producer.start();
// 关闭
producer.shutdown();
}
Related
I am trying to connect to websocket server endpoint using below code but I am not able to resolve container.connectToServer(this, cec, uri); this. This method is not able to take my class as Endpoint class. It's a spring boot project. If I don't pass config then it accepts but then it fails to connect to server and return 401. I have tried many online links but failed to resolve this issue. Need help in how to fix it.
#ClientEndpoint
public class TestClassEndpoint {
private Session userSession = null;
public TestClassEndpoint(URI uri) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientEndpointConfig cec = ClientEndpointConfig.Builder
.create().configurator(new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> headers) {
System.out.println("Setting user cookie in beforeRequest ...");
headers.put("Authorization", Arrays.asList("Basic base64encodedString"));
}
}).build();
container.connectToServer(this, cec, uri);
} catch (Exception e) {
e.printStackTrace();
}
}
#OnOpen
public void onOpen(Session session) {
this.userSession = session;
System.out.println("New connection established");
}
#OnMessage
public void onMessage(String message, Session session) {
System.out.println(message);
}
#OnClose
public void onClose(Session userSession, CloseReason reason) {
this.userSession = null;
System.out.println("connection closed");
}
#OnError
public void onError(Throwable t) {
}
private void sendMessage(ByteBuffer buffer) {
this.userSession.getAsyncRemote().sendBinary(buffer);
}
}
Main class
#SpringBootApplication
public class MainApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(TwilioPocApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
URI uri = UriComponentsBuilder.fromUriString("server_url").build().toUri();
new TestClassEndpoint(uri);
}
}
Following recommendations elsewhere I am attempting to parallelize my final inbound handler in a Netty pipeline as such
public final class EchoServer {
private EventLoopGroup group = new NioEventLoopGroup();
private UnorderedThreadPoolEventExecutor workers = new UnorderedThreadPoolEventExecutor(10);
public void start(int port) throws InterruptedException {
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
.handler(new ChannelInitializer<NioDatagramChannel>() {
#Override
protected void initChannel(NioDatagramChannel channel) throws Exception {
channel.pipeline().addLast(workers, new SimpleChannelInboundHandler<DatagramPacket>() {
#Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
System.err.println(packet);
// Simulated database delay that I have to wait to occur before repsonding
Thread.sleep(1000);
ctx.write(new DatagramPacket(Unpooled.copiedBuffer("goodbye", StandardCharsets.ISO_8859_1), packet.sender()));
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
}
});
}
});
b.bind(port).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
public void stop() {
group.shutdownGracefully();
}
}
I have ten clients that connect concurrently, as a test, and I am measuring execution time for handling all the requests. As expected with the 1 second delay and sequential execution it takes just over 10 seconds. I am trying to get execution down to somewhere sub 2 seconds to prove parallel handling.
From what I understand adding the handler to the pipeline with an explicitly assigned executor is supposed to parallelize that handlers work across the thread in the executor.
Instead of seeing a increase in performance, what I am finding is that my client is not receiving the responses when I add the parallel processing. The thread sleep is there to simulate the potential time it will take to write the incoming data to a database. Am I doing something obviously wrong here?
I worked around the apparently lack of Netty support for doing final end UDP processing in parallel using standard java concurrency mechanisms.
public final class EchoServer {
private EventLoopGroup group = new NioEventLoopGroup();
private ExecutorService executors = Executors.newFixedThreadPool(10);
public void start(int port) throws InterruptedException {
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<NioDatagramChannel>() {
#Override
protected void initChannel(NioDatagramChannel channel) throws Exception {
channel.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
#Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
CompletableFuture.runAsync(() -> {
System.err.println(packet);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("goodbye", StandardCharsets.ISO_8859_1),
packet.sender()));
}, executors);
}
#Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
}
});
}
});
b.bind(port).sync().channel().closeFuture().await();
} finally {
group.shutdownGracefully();
}
}
public void stop() {
group.shutdownGracefully();
}
}
I want to write Junit UT case for my websocket serverendpoint code using embedded Jetty.
i tried things explained in below link:
JUnit test with javax.websocket on embedded Jetty throws RejectedExecutionException: NonBlockingThread
I want to test my onMessage callback for websocket.
If i dont use server.join() method then the connection closes as soon as it opens.
If i use server.join() method nothing happens after joining.
Below is My code.
Server startup code::
public class EmbeddedJettyServer {
private final int port;
private Server server;
public EmbeddedJettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);
// Setup the basic application "context" for this application at "/"
// This is also known as the handler tree (in jetty speak)
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
try {
// Initialize javax.websocket layer
ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);
// Add WebSocket endpoint to javax.websocket layer
wscontainer.addEndpoint(WebSocketServer.class);
System.out.println("Begin start");
server.start();
server.dump(System.err);
server.join();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
public void stop() throws Exception {
server.stop();
LOGGER.info("Jetty server stopped");
}
public URI getWebsocketUri(Class<WebSocketServer> class1) {
return server.getURI();
}
}
Client Code:
#ClientEndpoint()
public class WebSocketClientJetty {
WebSocketContainer container;
public Session connect(URI uri) throws Exception {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
// Attempt Connect
Session session = container.connectToServer(WebSocketClientJetty.class,uri);
// return container.connectToServer(WebSocketClientJetty.class, uri);
session.getBasicRemote().sendText("Hello");
// Close session
// session.close();
return session;
} finally {
}
}
public void stop() throws Exception{
if (container instanceof LifeCycle) {
((LifeCycle) container).stop();
}
}
#OnOpen
public void onWebSocketConnect(Session sess)
{
System.out.println("Socket Connected: " + sess);
}
#OnMessage
public void onWebSocketText(String message)
{
System.out.println("Received TEXT message: " + message);
}
#OnClose
public void onWebSocketClose(CloseReason reason)
{
System.out.println("Socket Closed: " + reason);
}
#OnError
public void onWebSocketError(Throwable cause)
{
cause.printStackTrace(System.err);
}
}
Serverendpoint code:
#ServerEndpoint(value = "/echo",
encoders={JsonEncoder.class})
public class WebSocketServer {
private static final Logger LOGGER =
#OnOpen
public void onOpen(Session session){
System.out.println("onopen");
some code....
}
#OnMessage
public void onMessage(String message, Session session) throws IOException{
System.out.println("onmessage");
....
}
#OnClose
public void onClose(Session session){
System.out.println("onClose");
...
}
}
Ut case:
public class WebSocketJettyTest {
private static EmbeddedJettyServer server;
#ClassRule
public static final ExternalResource integrationServer = new ExternalResource() {
#Override
protected void before() throws Throwable {
System.out.println("Starting...");
server = new EmbeddedJettyServer(8080);
server.start();
System.out.println("Started");
}
};
#Before
public void setUp() throws Exception {
}
#After
public void shutdown() throws Exception {
server.stop();
}
#Test
public void testSocket() throws Exception {
/*URI uri = server.getWebsocketUri(WebSocketServer.class);*/
URI uri = URI.create("ws://localhost:8080/echo");
WebSocketClientJetty client = new WebSocketClientJetty();
Session session = client.connect(uri);
session.getBasicRemote().sendText("hello");
Thread.sleep(6000);
client.stop();
}
}
Drop the call to
server.join();
That just makes the current thread wait until the server thread stops.
Which is making it difficult for you.
I need to update my GUI based on client input. Calling my controller class method, from the background task works. But it can't update the GUI, because it is not the JavaFX application thread..please help.
I tried many of the related Q & A, but I am still confused.
Should I use Platform. runLater or Task ?
Here's my class where I create an instance of controller class
public class FactoryClass {
public static Controller_Gui1 createGUI() {
FXMLLoader fxLoader = new FXMLLoader();
fxLoader.setLocation(MainApp_Gui1.class.getResource("/com/Gui_1.fxml"));
AnchorPane anchorPane = null;
try {
anchorPane = (AnchorPane) fxLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
Controller_Gui1 controller_Gui1 = (Controller_Gui1) fxLoader
.getController();
Scene scene = new Scene(anchorPane);
//System.out.println(scene);
controller_Gui1.setScene(scene);
return controller_Gui1;
}
}
Controller class
#FXML
Button B1 = new Button();
#FXML
public void handleButton1() {
B1.setDisable(true);
}
Application class
public class MainApp_Gui1 extends Application {
Controller_Gui1 cGui;
#Override
public void start(Stage primaryStage) throws Exception {
initScene(primaryStage);
primaryStage.show();
System.out.println("asdasd");
SceneSetting sceneSetting = new SceneSetting();
//handleEvent();
System.out.println("after");
sceneSetting.setSceneAfter();
System.out.println("after2");
}
// creating scene
private void initScene(Stage primaryStage) throws IOException {
primaryStage.setScene(getScene(primaryStage));
}
public Scene getScene(Stage primaryStage) {
Controller_Gui1 cGui;
cGui = FactoryClass.createGUI();
return cGui.getScene();
}
public void ExcessFromOutside() {
Platform.runLater(new Runnable() {
public void run() {
System.out.println(Platform.isFxApplicationThread());
cGui.handleButton1();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
I want to call ExcessFromOutside() method from another thread.
I got a null pointer exception while trying to update the GUI
Here's my application class
public class MainAppGui1 extends Application {
Controller_Gui1 controller_Gui1;
#Override
public void start(Stage primaryStage) throws Exception {
initScene(primaryStage);
primaryStage.show();
}
// creating scene
public void initScene(Stage primaryStage) throws IOException {
FXMLLoader fxLoader = new FXMLLoader();
fxLoader.setLocation(MainApp_Gui1.class.getResource("/com/Gui_1.fxml"));
AnchorPane anchorPane=new AnchorPane();
anchorPane = (AnchorPane) fxLoader.load();
Controller_Gui1 controller_Gui1 = (Controller_Gui1) fxLoader.getController();
Scene scene = new Scene(anchorPane);
primaryStage.setScene(scene);
}
#FXML
public void ExcessFromOutside()
{
Platform.runLater(new Runnable() {
#Override
public void run() {
System.out.println("called atleast");
controller_Gui1.handleButton1();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
and this is the class from where i tried to update the GUI
public class Hudai {
public static void main(String args[]) throws InterruptedException
{
new Thread()
{
public void run()
{
MainAppGui1.main(null);
}
}.start();
Thread.sleep(5000);
MainAppGui1 m = new MainAppGui1();
m.ExcessFromOutside();
}
}
To disable your button in a different thread you can use Task's updateValue.
Task<Boolean> task = new Task<Boolean>() {
#Override
public Boolean call() {
... // The task that this thread needs to do
updateValue(true);
...
return null;
}
};
button.disableProperty().bind(task.valueProperty());
If you want to use a new thread to call a method, which alters the scene graph, the best chance you have is to use Platform.runLater() in it.
//code inside Thread
...
// code to run on the JavaFX Application thread
Platform.runLater(new Runnable() {
#Override
public void run() {
handleButton1();
}
});
...
You should get a NullPointerException when you run this program.
The problem is, the member of MainApp_Gui1
Controller_Gui1 cGui;
never gets a value.
Remove line "Controller_Gui1 cGui;" from this code:
public Scene getScene(Stage primaryStage) {
// Hudai hudai = new Hudai(primaryStage);
// return hudai.getScene();
Controller_Gui1 cGui;
cGui = FactoryClass.createGUI();
return cGui.getScene();
}
I am trying to get my Blackberry application to display a custom modal dialog, and have the opening thread wait until the user closes the dialog screen.
final Screen dialog = new FullScreen();
...// Fields are added to dialog
Application.getApplication().invokeAndWait(new Runnable()
{
public void run()
{
Application.getUiApplication().pushModalScreen(dialog);
}
});
This is throwing an Exception which says "pushModalScreen called by a non-event thread" despite the fact that I am using invokeAndWait to call pushModalScreen from the event thread.
Any ideas about what the real problem is?
Here is the code to duplicate this problem:
package com.test;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
public class Application extends UiApplication {
public static void main(String[] args)
{
new Application();
}
private Application()
{
new Thread()
{
public void run()
{
Application.this.enterEventDispatcher();
}
}.start();
final Screen dialog = new FullScreen();
final ButtonField closeButton = new ButtonField("Close Dialog");
closeButton.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
Application.getUiApplication().popScreen(dialog);
}
});
dialog.add(closeButton);
Application.getApplication().invokeAndWait(new Runnable()
{
public void run()
{
try
{
Application.getUiApplication().pushModalScreen(dialog);
}
catch (Exception e)
{
// To see the Exception in the debugger
throw new RuntimeException(e.getMessage());
}
}
});
System.exit(0);
}
}
I am using Component Package version 4.5.0.
Building on Max Gontar's observation that the Exception is not thrown when using invokeLater instead of invokeAndWait, the full solution is to implement invokeAndWait correctly out of invokeLater and Java's synchronization methods:
public static void invokeAndWait(final Application application,
final Runnable runnable)
{
final Object syncEvent = new Object();
synchronized(syncEvent)
{
application.invokeLater(new Runnable()
{
public void run()
{
runnable.run();
synchronized(syncEvent)
{
syncEvent.notify();
}
}
});
try
{
syncEvent.wait();
}
catch (InterruptedException e)
{
// This should not happen
throw new RuntimeException(e.getMessage());
}
}
}
Unfortunately, the invokeAndWait method cannot be overridden, so care must be used to call this static version instead.
Seems as though there's a bunch of code in there that's unnecessary.
public class Application extends UiApplication {
public static void main(String[] args)
{
new Application().enterEventDispatcher();
}
private Application()
{
final Screen dialog = new FullScreen();
final ButtonField closeButton = new ButtonField("Close Dialog");
closeButton.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
Application.getUiApplication().popScreen(dialog);
}
});
dialog.add(closeButton);
// this call will block the current event thread
pushModalScreen(dialog);
System.exit(0);
}
}
Use this:
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
pushScreen(new MyScreen());
}
});