Unity3d 使用Apache.NMS.ActiveMQ进行通信尝试,主、子线程问题记录
2023-09-27 14:27:29 时间
Unity3d 使用Apache.NMS.ActiveMQ进行通信尝试,主、子线程问题记录
尝试计划
计划通过一个小程序作为生产者(Producer),并在一定间隔向队列中加入消息,Unity3d端的话作为消费者(Consumer),接收该队列中的消息,并在收到消息后生成一个消息的内容作为名字的节点。
启动MQ服务
这一步直接百度实现的,大家自行搜吧。
Unity3D端实现
将下载的Apache.NMS.ActiveMQ.dll和Apache.NMS.dll放至工程的Plugins文件夹下,之后就是写代码,新建mq的消费者连接,并绑定监听(Listener):
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using System;
using UnityEngine;
using UnityEngine.UI;
public class MQTest : MonoBehaviour
{
public GameObject go;
void Start()
{
Connect();
}
void Connect()
{
try
{
IConnectionFactory factory = new ConnectionFactory("tcp://127.0.0.1:61616/");
IConnection connection = factory.CreateConnection();
connection.ClientId = "testing listener";
connection.Start();
ISession session = connection.CreateSession();
IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener", null, false);
consumer.Listener += new MessageListener(consumer_Listener);
Debug.LogError("服务器连接完成!!!!!!!!");
}
catch (System.Exception e)
{
Debug.LogError(e.Message);
}
}
void consumer_Listener(IMessage message)
{
ITextMessage msg = (ITextMessage)message;
Debug.LogError("接收到MQ数据: " + msg.Text);
GameObject temp = GameObject.Instantiate(go);
temp.name = msg.Text;
}
}
运行起来的效果:
Log显示已经收到数据,但未实例化对象;
尝试捕获异常
void consumer_Listener(IMessage message)
{
try
{
ITextMessage msg = (ITextMessage)message;
Debug.LogError("接收到MQ数据: " + msg.Text);
GameObject temp = GameObject.Instantiate(go);
temp.name = msg.Text;
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
找到问题了,不能在子线程里实例化对象。
解决方案
先将MQ消息记录在列表,通过FixedUpdate或者Update里面读取处理。
List<string> MsgList = new List<string>();
void Update() {
if (MsgList.Count > 0) {
GameObject temp = GameObject.Instantiate(go);
temp.name = MsgList[0];
Destroy(temp, 3);
MsgList.RemoveAt(0);
}
}
void consumer_Listener(IMessage message)
{
try
{
ITextMessage msg = (ITextMessage)message;
Debug.LogError("接收到MQ数据: " + msg.Text);
MsgList.Add(msg.Text);
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
相关文章
- apache安装 mod_evasive
- 【认证】Apache Shiro对象概念
- 对于学习apache软件基金会顶级项目源码的一点思路(转)
- MyException--org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ###
- The type org.apache.commons.cli.Options cannot be resolved. It is indirectly referenced from required .class files
- 阿里向Apache捐赠消息中间件RocketMQ
- 已解决java.lang.ClassNotFoundException: org.apache.htrace.SamplerBuilder
- 已解决Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile异常的正确解决方法,亲测有效
- 恭喜!Apache Hudi社区新晋多位Committer
- Apache Flink 开发环境搭建和应用的配置、部署及运行
- Apache Impala 的安装部署
- com.sun.org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException
- [ vulhub漏洞复现篇 ] Apache Log4j Server 反序列化命令执行漏洞 CVE-2017-5645