Java RabbitMQ

package com.dxc.cred.service;

import com.dxc.cred.utils.ConnectionUtils;
import com.rabbitmq.client.*;
import org.hyperledger.indy.sdk.IndyException;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import javax.annotation.PostConstruct;
@Component
public class RabbitMQServiceImpl {
    
	@Autowired
    private IndyServiceImpl indyService;
    private final static String CRED_OFFER_REQUEST_QUEUE = "credentialOfferRequest";
    private final static String CRED_OFFER_RESPONSE_QUEUE = "credentialOfferResponse_";
    private final static String CRED_REQUEST_QUEUE = "credentialRequest";
    private final static String CRED_RESPONSE_QUEUE = "credentialResponse_";
    
	private static final String credOfferReqTest = "{\n"
			 + "  \"type\": \"credentialOfferResponse\",\n"
			 + "   \"value\": { \n"
			+ " 	    credentialName: \"transcript\",\n"
			+ " 	    email: \"***@***.com\",\n"
				+ "     token: \"148290\"\n"
				+ " 	  },\n"
				+ "     src: \"13579\"\n"
				+ " 		}";
	private static final String credReqTest = "{\n"
			 + "  \"type\": \"credentialOfferResponse\",\n"
			 + "   \"value\": { \n"
			+ " 	    email: \"***@***.com\",\n"
			+ " 	    credentialOffer: \"credentialOffer\",\n"
				+ "     credentialReq: \"credentialReq\"\n"
				+ " 	  },\n"
				+ "     src: \"24680\"\n"
				+ " 		}";
    
    private static Connection connection = null;
    private static Channel channel = null;
    
    @PostConstruct
    public void init() throws IOException, TimeoutException, InterruptedException, ExecutionException, IndyException, JSONException{
    	initQueue();
    	test1();
    }
    
    public static void main(String[] argv) throws Exception {
        JSONObject offerReqJson = new JSONObject("]");
        String credName = (String)offerReqJson.getJSONObject("value").get("credentialName1");
    }   
    
    public boolean test1() throws InterruptedException, ExecutionException, IndyException, IOException, JSONException, TimeoutException {    	
    	indyService.test();
    	//indyService.init();
    //	publishMsg(CRED_OFFER_REQUEST_QUEUE, credOfferReqTest);
    //	publishMsg(CRED_REQUEST_QUEUE, credReqTest);    	
    	return true;
    }
    
    public boolean initQueue() throws IOException, TimeoutException {
    	Connection connection = ConnectionUtils.getConnection();
    	channel = connection.createChannel();
    	channel.queueDeclare(CRED_OFFER_REQUEST_QUEUE, false, false, false, null);
    	channel.queueDeclare(CRED_REQUEST_QUEUE, false, false, false, null);
    	
	 Consumer consumerOfferReq = new DefaultConsumer(channel) {
	      @Override
	      public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
	          throws IOException {
	        String message = new String(body, "UTF-8");
	        System.out.println(" [x] Received from Offer Request'" + message + "'");
	        String response = "";
			try {
				response = indyService.createCredOfferResponse(message);
				
				JSONObject offerReqJson = new JSONObject(message);
		        String src = (String)offerReqJson.get("src");
		        String queue = CRED_OFFER_RESPONSE_QUEUE + src;
				channel.queueDeclare(queue, false, false, false, null);
				
				publishMsg(queue, response); 
				System.out.println(" [x] Received from Offer Response'" + response + "'");
			} catch (JSONException e) {
				e.printStackTrace();
			}	          
	      }
	    };
	 channel.basicConsume(CRED_OFFER_REQUEST_QUEUE, true, consumerOfferReq);
	 
	 Consumer consumerCredrReq = new DefaultConsumer(channel) {
	      @Override
	      public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
	          throws IOException {
	        String message = new String(body, "UTF-8");
	        System.out.println(" [x] Received from Credential Request'" + message + "'");
	        String response = "";
			try {
				response = indyService.createCredResponse(message);
				
		        JSONObject credReqJson = new JSONObject(message);
		        String src = (String)credReqJson.get("src");
		        String queue = CRED_RESPONSE_QUEUE + src;
				channel.queueDeclare(queue, false, false, false, null);
				
				publishMsg(queue, response); 				
				System.out.println(" [x] Received from Credential Response'" + response + "'");
			} catch (JSONException e) {
				e.printStackTrace();
			}
	      }
	    };
	 channel.basicConsume(CRED_REQUEST_QUEUE, true, consumerCredrReq);
    	    
    	return true;
    }
    
    public void close() throws IOException, TimeoutException {
        channel.close();
        connection.close();
    }
    
    public void publishMsg(String queueName, String msg) throws UnsupportedEncodingException, IOException {
    	channel.basicPublish("", queueName, null, msg.getBytes("UTF-8"));
    }
}

 

Java RabbitMQ 是一个开源的消息中间件,它实现了高级消息队列协议(AMQP)标准,可以在分布式系统中用于异步消息传递。RabbitMQ 使用生产者、消费者和代理(broker)三个概念来实现消息传递。 在 Java 中使用 RabbitMQ 需要使用官方提供的 Java 客户端库,可以通过 Maven 或 Gradle 等构建工具引入。在使用 RabbitMQ 时,首先需要创建一个连接和一个通道(channel),然后创建生产者和消费者来发送和接收消息。 例如,以下是一个简单的 Java RabbitMQ 生产者示例: ```java import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; public class RabbitMQProducer { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); // 创建连接 Connection connection = factory.newConnection(); // 创建通道 Channel channel = connection.createChannel(); // 声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); // 发送消息 String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); // 关闭通道和连接 channel.close(); connection.close(); } } ``` 上述代码会向名为 "hello" 的队列发送一条消息,然后关闭连接和通道。类似地,可以创建一个消费者来接收消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值