Advertisement
vitareinforce

RMQ on Java

Apr 18th, 2019
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.74 KB | None | 0 0
  1. /**
  2. * Class untuk definisi function RMQ
  3. */
  4. public class RMQ {
  5.  
  6. // Load Global Configuration
  7. Settings settings = new Settings();
  8.  
  9. // Setup RMQ Configuration (Ganti dengan setting akun RMQ nya)
  10. String user = "user"
  11. String pass = "pass"
  12. String host = "host"
  13. String vhost = "vhost"
  14. String exchanges_name = "exchange"
  15. String queue_name_publish = "queue_publish"
  16. String queue_name_subscribe = "queue_subscribe"
  17. String routingKey = "routing key"
  18.  
  19. // Define new Connection Factory
  20. ConnectionFactory factory = new ConnectionFactory();
  21.  
  22. /**
  23. * Setup Connection Factory
  24. * Load Setting Connection RMQ Sebagai Parameter Koneksi
  25. */
  26. public void setupConnectionFactory() {
  27. try {
  28. factory.setAutomaticRecoveryEnabled(false);
  29. factory.setUri("amqp://"+user+":"+pass+"@"+host);
  30. factory.setVirtualHost(vhost);
  31. } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException e1) {
  32. e1.printStackTrace();
  33. }
  34. }
  35.  
  36. /**
  37. * Publish data lewat RMQ
  38. * @param message
  39. */
  40. public void publish(String message) {
  41. try {
  42. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  43. StrictMode.setThreadPolicy(policy);
  44.  
  45. Connection connection = factory.newConnection();
  46. Channel channel = connection.createChannel();
  47.  
  48. String messageOn = message ;
  49. channel.basicPublish("", queue_name_publish,null,messageOn.getBytes());
  50.  
  51. } catch (IOException e) {
  52. Log.d("Publish Error", e.getMessage());
  53. } catch (TimeoutException e) {
  54. Log.d("Publish Error", e.getMessage());
  55. } catch (Exception e) {
  56. Log.d("Publish Error", e.getMessage());
  57. }
  58.  
  59. }
  60.  
  61. /**
  62. * Optional, Send Speed for threading speed
  63. * @throws InterruptedException
  64. */
  65. public void SendSpeed() throws InterruptedException {
  66. Thread.sleep(500); //0.5 sec
  67. }
  68.  
  69. /**
  70. * Fungsi untuk subscribe data RMQ
  71. * @param handler
  72. * @param subscribeThread
  73. */
  74. public void subscribe(final Handler handler, Thread subscribeThread)
  75. {
  76. subscribeThread = new Thread(new Runnable() {
  77. @Override
  78. public void run() {
  79. while(true) {
  80. try {
  81. Connection connection = factory.newConnection();
  82. Channel channel = connection.createChannel();
  83. channel.basicQos(0);
  84. channel.queueBind(queue_name_subscribe, exchanges_name, routingKey);
  85. QueueingConsumer consumer = new QueueingConsumer(channel);
  86. channel.basicConsume(queue_name_subscribe, true, consumer);
  87. QueueingConsumer.Delivery delivery = consumer.nextDelivery();
  88.  
  89. if (delivery != null){
  90.  
  91. try{
  92.  
  93. String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
  94. Log.d("ConsumeDataRMQ", "MessageConsumed" + message);
  95.  
  96. Message msg = handler.obtainMessage();
  97. Bundle bundle = new Bundle();
  98.  
  99. bundle.putString("msg", message);
  100. msg.setData(bundle);
  101. handler.sendMessage(msg);
  102.  
  103. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
  104.  
  105. }catch (Exception e){
  106. channel.basicReject(delivery.getEnvelope().getDeliveryTag(),true);
  107. }
  108. }
  109. } catch (InterruptedException e) {
  110. break;
  111. } catch (Exception e1) {
  112. Log.d("", "Connection broken: " + e1.getClass().getName());
  113. try {
  114. Thread.sleep(4000); //sleep and then try again
  115. } catch (InterruptedException e) {
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. });
  122. subscribeThread.start();
  123. }
  124. }
  125.  
  126. --------------
  127. Cara Make di Main Activity
  128. 1. Buat fungsi show notification dulu
  129. public void showNotification( String title, String body) {
  130. Context context = getApplicationContext();
  131. Intent intent = getIntent();
  132.  
  133. NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  134. int notificationId = 1;
  135. String channelId = "channel-01";
  136. String channelName = "Channel Name";
  137. int importance = NotificationManager.IMPORTANCE_HIGH;
  138.  
  139. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  140. NotificationChannel mChannel = new NotificationChannel(
  141. channelId, channelName, importance);
  142. notificationManager.createNotificationChannel(mChannel);
  143. }
  144.  
  145. NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
  146. .setSmallIcon(R.drawable.bawasluicon)
  147. .setContentTitle(title)
  148. .setContentText(body);
  149.  
  150. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
  151. stackBuilder.addNextIntent(intent);
  152. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
  153. 0,
  154. PendingIntent.FLAG_UPDATE_CURRENT
  155. );
  156. mBuilder.setContentIntent(resultPendingIntent);
  157.  
  158. notificationManager.notify(notificationId, mBuilder.build());
  159. }
  160.  
  161. 2. Subscribe ke RMQ ketika menerima data bakal panggil Subscribe notification di activity
  162. 2.1 Inisialisasi dulu di activity dengan
  163. RMQ rmq = new RMQ();
  164.  
  165. 2.2 Kemudian di On Create Panggil Inisialisasi Koneksi RMQ dan panggil fungsi subscribe notification
  166. rmq.setupConnectionFactory();
  167. subscribeNotification();
  168.  
  169. 2.2.1 Fungsi untuk subscribe notificationnya seperti ini
  170. private void subscribeNotification() {
  171. final Handler incomingMessageHandler = new Handler() {
  172. @Override
  173. public void handleMessage(Message msg) {
  174. String title = "Pengumuman";
  175. String message = msg.getData().getString("msg");
  176. Log.d("RMQMessage", message);
  177.  
  178. showNotification(title, message);
  179. }
  180. };
  181. rmq.subscribe(incomingMessageHandler,subscribeThread);
  182. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement