NutzCN Logo
问答 nutzwk怎么在新建的线程中获取dao来操作数据库
发布于 2359天前 作者 qq_43bc7d85 1872 次浏览 复制 上一个帖子 下一个帖子
标签: nutzwk
package cn.wizzer.app.web.commons.core;

import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.client.HelloClientAioHandler;
import cn.wizzer.app.web.commons.ext.pubsub.WebPubSub;
import org.jim.common.ImAio;
import org.jim.common.packets.ChatBody;
import org.jim.common.packets.Command;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.tcp.TcpPacket;
import org.nutz.boot.NbApp;
import org.nutz.integration.jedis.JedisAgent;
import org.nutz.integration.shiro.ShiroSessionProvider;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Node;
import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * Created by wizzer on 2018/3/16.
 */
@IocBean(create = "init", depose = "depose")
@Modules(packages = "cn.wizzer")
@Localization(value = "locales/", defaultLocalizationKey = "zh_CN")
@Encoding(input = "UTF-8", output = "UTF-8")
@ChainBy(args = "chain/nutzwk-mvc-chain.json")
@SessionBy(ShiroSessionProvider.class)
public class WebPlatformMainLauncher {
//    private static final Log log = Logs.get();
    @Inject("refer:$ioc")
    private Ioc ioc;
    @Inject
    private PropertiesProxy conf;
    @Inject
    private JedisAgent jedisAgent;
    @Inject
    private Globals globals;//注入一下为了初始化
    @Inject
    private WebPubSub webPubSub;//注入一下为了初始化


    //服务器节点
    public static Node serverNode = new Node("192.168.1.108",8888);

    //handler, 包括编码、解码、消息处理
    public static ClientAioHandler aioClientHandler = new HelloClientAioHandler();

    //事件监听器,可以为null,但建议自己实现该接口,可以参考showcase了解些接口
    public static ClientAioListener aioListener = null;

    //断链后自动连接的,不想自动连接请设为null
    private static ReconnConf reconnConf = new ReconnConf(5000L);

    //一组连接共用的上下文对象
    public static ClientGroupContext clientGroupContext = new ClientGroupContext(aioClientHandler, aioListener, reconnConf);

    public static AioClient aioClient = null;
    public static ClientChannelContext clientChannelContext = null;

    /**
     * 启动程序入口
     */
    public static void main(String[] args) throws Exception {

        //clientGroupContext.setHeartbeatTimeout(org.tio.examples.helloworld.common.Const.TIMEOUT);
        clientGroupContext.setHeartbeatTimeout(0);
        aioClient = new AioClient(clientGroupContext);
        clientChannelContext = aioClient.connect(serverNode);
        //连上后,发条消息玩玩
        send();

        NbApp nb = new NbApp().setArgs(args).setPrintProcDoc(true);
        nb.getAppContext().setMainPackage("cn.wizzer");
        System.out.println("");
        nb.run();
    }

    private static void send() throws Exception {
        byte[] loginBody = new LoginReqBody("web_client","123").toByte();
        TcpPacket loginPacket = new TcpPacket(Command.COMMAND_LOGIN_REQ,loginBody);
        ImAio.send(clientChannelContext, loginPacket);//先登录;
        ChatBody chatBody = new ChatBody()
                .setFrom("web_client")
                .setTo("admin")
                .setMsgType(0)
                .setChatType(1)
                .setGroup_id("100")
                .setContent("Socket普通客户端消息测试!");
        TcpPacket chatPacket = new TcpPacket(Command.COMMAND_CHAT_REQ,chatBody.toByte());
        ImAio.send(clientChannelContext, chatPacket);
    }


    public void init() {


    }

    public void depose() {

    }
}

package cn.wizzer.app.web.commons.client;

import org.jim.common.ImAio;
import org.jim.common.packets.ChatBody;
import org.jim.common.packets.Command;
import org.jim.common.packets.LoginReqBody;
import org.jim.common.tcp.TcpPacket;
import org.tio.client.AioClient;
import org.tio.client.ClientChannelContext;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Node;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 
 * 作者: WChao 创建时间: 2017年8月30日 下午1:05:17
 */
public class HelloClientStarter {
	//服务器节点
	public static Node serverNode = new Node("192.168.1.108",8888);

	//handler, 包括编码、解码、消息处理
	public static ClientAioHandler aioClientHandler = new HelloClientAioHandler();

	//事件监听器,可以为null,但建议自己实现该接口,可以参考showcase了解些接口
	public static ClientAioListener aioListener = null;

	//断链后自动连接的,不想自动连接请设为null
	private static ReconnConf reconnConf = new ReconnConf(5000L);

	//一组连接共用的上下文对象
	public static ClientGroupContext clientGroupContext = new ClientGroupContext(aioClientHandler, aioListener, reconnConf);

	public static AioClient aioClient = null;
	public static ClientChannelContext clientChannelContext = null;

	/**
	 * 启动程序入口
	 */
	public static void main(String[] args) throws Exception {
		//clientGroupContext.setHeartbeatTimeout(org.tio.examples.helloworld.common.Const.TIMEOUT);
		clientGroupContext.setHeartbeatTimeout(0);
		aioClient = new AioClient(clientGroupContext);
		clientChannelContext = aioClient.connect(serverNode);
		//连上后,发条消息玩玩
		send();
	}

	private static void send() throws Exception {
		byte[] loginBody = new LoginReqBody("web_client","123").toByte();
		TcpPacket loginPacket = new TcpPacket(Command.COMMAND_LOGIN_REQ,loginBody);
		ImAio.send(clientChannelContext, loginPacket);//先登录;
//		ChatBody chatBody = new ChatBody()
//				.setFrom("hello_client")
//				.setTo("admin")
//				.setMsgType(0)
//				.setChatType(1)
//				.setGroup_id("100")
//				.setContent("Socket普通客户端消息测试!");
//		TcpPacket chatPacket = new TcpPacket(Command.COMMAND_CHAT_REQ,chatBody.toByte());
//		ImAio.send(clientChannelContext, chatPacket);
	}
}

package cn.wizzer.app.web.commons.client;

import cn.wizzer.app.da.modules.models.Da_bj;
import cn.wizzer.app.da.modules.models.Da_bjgx;
import cn.wizzer.app.da.modules.models.Da_lxr;
import cn.wizzer.app.sb.modules.models.Sb_gjsj;
import org.jim.common.Const;
import org.jim.common.Protocol;
import org.jim.common.packets.Command;
import org.jim.common.tcp.TcpPacket;
import org.jim.common.tcp.TcpServerDecoder;
import org.jim.common.tcp.TcpServerEncoder;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.DaoUp;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.AioHandler;
import org.tio.core.intf.Packet;

import java.nio.ByteBuffer;

/**
 * 
 * 版本: [1.0]
 * 功能说明: 
 * 作者: WChao 创建时间: 2017年8月30日 下午1:10:28
 */

public class HelloClientAioHandler implements AioHandler,ClientAioHandler
{
	private static final Log log = Logs.get();
	/** 
	 * 处理消息
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception
	{
		try {
			DaoUp.me().init("nutzdb.properties");
			Dao dao = DaoUp.me().dao();

		TcpPacket helloPacket = (TcpPacket)packet;
		byte[] body = helloPacket.getBody();
		if (body != null)
		{
			String str = new String(body, Const.CHARSET);
//			NutMap data=NutMap.WRAP(str);
			NutMap data=NutMap.WRAP(NutMap.WRAP(str).getString("data"));
//			if(data==null)return;
//			List<Sb_gjsj> gjsjs=data.getList("content",Sb_gjsj.class);
			if(data==null)return;
			if(data.getString("content")==null)return;
			String content=data.getString("content");
			System.out.println("收到消息:" + content);
			content=content.replace("[","");
			content=content.replace("]","");
			content=content.replace("s:","");
			content=content.replace("ms","");
			System.out.println("收到消息:" + content);
			System.out.println("收到消息:" + NutMap.WRAP(content));
			Sb_gjsj gjsj=Json.fromJson(Sb_gjsj.class,content);
//			System.out.println("收到消息:" +gjsj );

			String message   = "【BBI】尊敬的用户,您好!{1}发生告警,请关注\n" +
					"设备:{2}\n" +
					"事件:{3}\n" +
					"时间:{4}\n" +
					"有问题请及时联系相关人员";
			Da_bj bj=dao.fetch(Da_bj.class, Cnd.where("dwdm","=",data.get("IOServerName")).and("cld","=",data.get("TagName")));
			if(bj==null)return ;
			Da_bjgx bjgx=dao.fetch(Da_bjgx.class,Cnd.where("sjid","=",bj.getId()));
			if(bjgx==null)return ;
			Da_lxr lxr=dao.fetch(Da_lxr.class,bjgx.getPhone());
			if(lxr==null)return ;


			gjsj.setId(bj.getId());
			dao.insert(gjsj);
			String phone = lxr.getPhone();
//			gjsj.setId(lxr.get("sjid"));
			System.out.println("收到消息:" +phone );
			DaoUp.me().close();
		}

		return;
		} catch (Exception e) {
			log.info(e);
}
	}



	/**
	 * 编码:把业务消息包编码为可以发送的ByteBuffer
	 * 总的消息结构:消息头 + 消息体
	 * 消息头结构:    4个字节,存储消息体的长度
	 * 消息体结构:   对象的json串的byte[]
	 */
	@Override
	public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext)
	{
		TcpPacket tcpPacket = (TcpPacket)packet;
		return TcpServerEncoder.encode(tcpPacket, groupContext, channelContext);
	}
	

	public TcpPacket decode(ByteBuffer buffer,int limit, int position, int readableLength,ChannelContext channelContext) throws AioDecodeException {
		TcpPacket tcpPacket = TcpServerDecoder.decode(buffer, channelContext);
		return tcpPacket;
	}
	
	private static TcpPacket heartbeatPacket = new TcpPacket(Command.COMMAND_HEARTBEAT_REQ,new byte[]{Protocol.HEARTBEAT_BYTE});

	/** 
	 * 此方法如果返回null,框架层面则不会发心跳;如果返回非null,框架层面会定时发本方法返回的消息包
	 */
	@Override
	public TcpPacket heartbeatPacket()
	{
		return heartbeatPacket;
	}
}

5 回复

public getDao() {
if (dao == null) {
Ioc ioc = Mvcs.getIoc();
if (ioc == null) {
NutMvcContext context = Mvcs.ctx();
Set set = context.iocs.keySet();
for (String key : set) {
ioc = context.iocs.get(key);//就一个而已
}
}
if (ioc != null) {
dao = ioc.get(Dao.class, "dao");
}else {
log.error("ioc 为空啊!我也不知道怎么办啊~~");
}
}
}

大概是这种写法,我是这样用的

添加回复
请先登陆
回到顶部