js封装函数的步骤一个函数

查看: 5784|回复: 12
封装webkit库的几个常用函数
主题帖子积分
本帖最后由 carl 于
11:07 编辑
webkit相对web.form主要是cookie这些会各自独立,显示速度也会比较快等等,所以还是挺好用的,
用的过程中,根据web.form库封装了几个常用函数,做为自定义库使用,有不足之处请自行扩展。
webkit函数扩展库:
webkit = class {
& & & & ctor( winform ){
& & & & & & & & this = web.kit.form( winform );& & & & & & & &
& & & & };
& & & &
& & & & getEle = function( id, frame ){
& & & & & & & & if( type(id) == &table& )
& & & & & & & &
& & & & & & & & try{
& & & & & & & & & & & & ele = this.document.getElementById(id);
& & & & & & & & & & & & if( !ele ){
& & & & & & & & & & & & & & & & var eles = this.document.getElementsByName(id);& & & &
& & & & & & & & & & & & & & & & ele = eles[0]
& & & & & & & & & & & & }
& & & & & & & & }
& & & & & & & &
& & & & }
& & & &
& & & & dispatch = function(ele, commandName) {
& && &&&var event = this.document.createEvent(&Event&);
& && &&&event.initEvent(commandName, true, true);
& && &&&ele.dispatchEvent(event)
& & & & }
& & & &
& & & & click = function( eleName,min=1,max=500,frame ){
& & & & & & & & var ele = this.getEle(eleName, frame);
& & & & & & & & if( !ele )
& & & & & & & & if(ele.tagName==&INPUT& or ele.tagName==&BUTTON&){
& & & & & & & & & & & & ele.click()
& & & & & & & & & & & &
& & & & & & & & }else {
& & & & & & & & & & & & this.dispatch(ele, &click&)
& & & & & & & & & & & &
& & & & & & & & }
& & & & }
& & & &
& & & & waitEle = function(name,frame,timeout,complete=true,test){
& & & & & & & & return ..win.wait(
& & & & & & & & & & & & function(){
& & & & & & & & & & & & & & & & return this.getEle(name);
& & & & & & & & & & & & },this.getForm().hwnd,timeout,200
& & & & & & & & )
& & & & }
& & & &
& & & & [&select&] = function(eleName,v,sel=true, frame){
& & & & & & & & var opt,child,value,
& & & & & & & & var ele = this.getEle(eleName,frame);
& & & & & & & & if( string.cmp(ele.tagName,&select&) )
& & & & & & & & if(ele){
& && & & & & & & & & & & & if(type(v)==type.number and v & ele.length){
& && & & && & & & & & & & & & & & & & opt = ele.options[i];
& && & & & & & & & & & & & }else{
& && & & & & & & & & & & & & & & & v = sel ? string.lower(v) :
& && & & && & & & & & & & & & & & & & for(i=0;ele.length-1;1){
& && & & && & & & & & & & & & & & & & & & & & child = ele.options[i];
& && & & && & & & & & & & & & & & & & & & & & if( !child )
& && & & && & & & & & & & & & & & & & & & & & value = sel ? string.lower(child.value) :
& && & & && & & & & & & & & & & & & & & & & & text = sel ? string.lower(child.text) :
& & & & & & & & & & & & & & & & & & & & if(value == v or text == v){
& & & & & & & & & & & & & & & & & & & & & & & & opt =
& & & & & & & & & & & & & & & & & & & & & & & &
& & & & & & & & & & & & & & & & & & & & }
& & & & & & & & & & & & & & & & }
& && & & & & & & & & & & & }
& & & & & & & & }
& & & & & & & & if( opt ){
& & & & & & & & & & & & opt.selected =
& & & & & & & & & & & & if( ele.onchange ) ele.fireEvent(&onchange&);
& & & & & & & & }
& & & & & & & &
& & & & }
& & & &
& & & & setEle = function(eleName,val,name,frame){
& & & & & & & & var ele = this.getEle(eleName,frame);
& & & & & & & & if(!ele) return null,&未找到节点&;
& & & & & & & &
& & & & & & & & if( type(val) == type.table ){
& & & & & & & & & & & & for(k,v in val)
& & & & & & & & & & & & & & & & this.setEle(eleName,v,k,frame);
& & & & & & & & }
& & & & & & & & elseif(name){
& & & & & & & & & & & & ele[name] =
& & & & & & & & }
& & & & & & & & elseif( string.cmp(ele.tagName,&textArea&) == 0&&){
& & & & & & & & & & & & ele.innerHTML =
& & & & & & & & }
& & & & & & & & elseif( !string.cmp(ele.tagName,&input&) ){
& & & & & & & & & & & & select(ele.type) {
& & & & & & & & & & & & & & & & case &radio&,&checkbox& {
& & & & & & & & & & & & & & & & & & & & ele.checked =
& & & & & & & & & & & & & & & & };
& & & & & & & & & & & & & & & & else {
& & & & & & & & & & & & & & & & & & & & ele.value =
& & & & & & & & & & & & & & & & };
& & & & & & & & & & & & };
& & & & & & & & };
& & & & & & & & elseif(&&string.cmp(ele.tagName,&select&) == 0 ){
& & & & & & & & & & & & this.select( ele,val );
& & & & & & & & }
& & & & & & & &
& & & & };
& & & & getHtml = function(){
& & & & & & & &
& & & & & & & & try{
& & & & & & & & & & & & html = this.document.documentElement.outerHTML;
& & & & & & & & }
& & & & & & & & return html:&&;
& & & & }
& & & &
namespace webkit{
& & & & import web.kit.
& & & &
& & & & string = ..
}
/**intellisense()
carl.webkit = web.kit扩展库
carl.webkit( __/*winform对象*/ ) = 创建webkit窗体
?carl.webkit = !web_kit_view.
!ele.src = 源文件地址
!ele.fireEvent(&onclick&) = 自动触发element元素节点的事件脚本.
!ele.click() = 触发onclick 事件来模拟单击
!ele.focus() = 使得元素得到焦点并执行由 onfocus 事件指定的代码
!ele.hasFocus() = 是否拥有焦点
!ele.blur() = 使元素失去焦点并触发onblur事件&&
!ele.setAttribute(&属性名__&,&属性值&)&&= 修改属性\n也可以直接写 ele.属性名字 = 值
!ele.getAttribute(&属性名__/*属性名*/&)&&= 获取属性\n也可以直接写 var 返回值=ele.属性名字
!ele.getAttributeNode(&__/*属性名*/&) = 获取attribute对象
!ele.hasChildNodes = 对象是否有子对象的值。
!ele.appendChild(__) = 给对象添加一个子节点
!ele.innerHTML = 返回节点内的HTML代码
!ele.outerHTML = 返回该节点的HTML代码
!ele.innerText = 设置或获取对象的文本
!ele.outerText = 设置或获取对象的文本
!ele.insertAdjacentHTML(&beforeBegin&,__/*HTML代码*/) = 在节点之前插入HTML
!ele.insertAdjacentHTML(&afterBegin&,__/*HTML代码*/) = 在节点内部最前面插入HTML
!ele.insertAdjacentHTML(&beforeEnd&,__/*HTML代码*/) = 在节点内部最后面插入HTML
!ele.insertAdjacentHTML(&afterEnd&,__/*HTML代码*/) = 在节点之后插入HTML
!ele.insertAdjacentText(&beforeBegin&,__/*文本*/) = 在节点之前插入文本
!ele.insertAdjacentText(&afterBegin&,__/*文本*/) = 在节点内部最前面插入文本
!ele.insertAdjacentText(&beforeEnd&,__/*文本*/) = 在节点内部最后面插入文本
!ele.insertAdjacentText(&afterEnd&,__/*文本*/) =&&在节点之后插入文本
!ele.insertBefore(__/*新节点对象*/) = 第二个参数可选指定一个子节点对象\n在该节点前插入新节点,忽略则插入到最后面.
!ele.checked = 复选框、单选框等选中状态
!ele.form.submit() = 自动提交表单
!ele.elements[&name值或索引&] = 表单控件集合,非表单节点该属性无性.\n索引可以为数值或字符串,\n如果有同名控件,可使用第二个参数指定在该集合中的索引.
!ele.elements[] = !ele.
!ele.getElementsByTagName(&__&) = 获取基于指定元素名称的对象集合
!ele.getElementsByTagName() = !ele.
!ele.contains(ele2__) = 判断一个节点是否包含另外一个节点
!ele.selected = 设置为下拉选框选中项
!ele.href = 超链接网址
!ele.value = input控件值
!ele.tagName = 获取对象的标签名称
!ele.scrollHeight =&&获取对象的滚动高度。
!ele.scrollLeft =&&设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离。
!ele.scrollTop = 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离。
!ele.scrollWidth = 获取对象的滚动宽度。
!ele.className = 设置或获取对象的CSS样式类
!ele.hasChildNodes() = 对象是否有子对象的值。
!ele.offsetParent = 获取定义对象 offsetTop 和 offsetLeft 属性的容器对象的引用
!ele.offsetLeft = 相对于offsetParent对象的左侧位置.
!ele.offsetTop =&&相对于offsetParent对象的顶端位置.
!ele.offsetWidth = 包括边线的宽度
!ele.offsetHeight&&= 包括边线的高度
!ele.ownerDocument = document.
!ele.id = 获取标识对象的字符串
!ele.uniqueID = 对象自动生成的唯一标识符
!ele.name = 设置或获取对象的名称
!ele.length = 节点集合长度
!ele.nodeName = 获取特定结点类型的名称。
!ele.nodeType = 获取所需结点的类型。
!ele.nodeValue = 设置或获取结点的值。
!ele.parentElement = 获取对象层次中的父对象\n!ele.
!ele.parentNode = 获取文档层次中的父对象\n!ele.
!ele.childNodes() = !ele.
!ele.children() = !ele.
!ele.getReadyState() = 获取对象的当前状态。 \n'uninitialized','loading','interactive','loaded' 'complete'
!ele.sourceIndex = 获取对象在源序中的依次位置
!ele.title = 提示信息
!ele.attributes(&name__/*属性名称*/&) = 对象标签属性的集合指定位置的对象&&
!ele.childNodes(0__) =&&对象直接后代的 HTML元素和TextNode对象的集合指定位置的对象
!ele.children(0__) =&&获取作为对象直接后代的DHTML对象的集合指定位置的对象
!ele.style.background = 背景
!ele.style.display = 显示
!ele.style.cursor = 鼠标指针
!ele.style.height = 高度
!ele.style.width = 宽度
!ele.style.top = 顶部位置
!ele.style.left = 左侧位置
!ele.style.margin = 外边距
!ele.style.padding = 内边距
!ele.contentEditable = @.contentEditable = &true__&
!ele.firstChild =&&childNodes集合的第一个子对象的引用\n!ele.
!ele.lastChild = childNodes集合中最后一个子对象的引用\n!ele.
!ele.nextSibling = 返回当前节点的兄弟下一个节点(下一个兄弟节点)\n!ele.
!ele.previousSibling = 返回紧挨当前节点、位于它之前的兄弟节点(上一个兄弟节点)\n!ele.
!ele.hidefocus = 是否隐藏焦点选框
!ele.getAttributeNode() = !ele_attribute_node.
!ele.attributes() = !ele_attribute_node.
!ele_attribute_node.nodeName = 获取特定结点类型的名称
!ele_attribute_node.nodeType = 获取所需结点的类型
!ele_attribute_node.nodeValue = 设置或获取结点的值
!ele_attribute_node.specified =&&获取是否指定了该属性
!ele_attribute_node.value =&&设置或获取对象的值
!web_kit_view.getEle() = !ele.
!web_kit_view.select() = !ele.
!web_kit_view.setEle() = !ele.
!ele[] = !ele.
!web_kit_view.waitEle(.(&ID或名称&,&框架名&,超时值,等待加载完成,页面加载完成允许返回空) = 返回一个节点对象,除参数一以外,其他能数可选\n第三个参数指定超时值(单位为毫秒)\n如果不需要节点完全加载,指定参数三为true\n如果网页加载完成节点不存在允许返回空,指定参数四为true
!web_kit_view.getEle(&__&) = 返回一个节点对象或框架内子节点对象
!web_kit_view.getEle(&__&) = 返回一个节点对象或框架内子节点对象
!web_kit_view.getEle(&__&,&框架名字&) = 返回一个节点对象或框架内子节点对象
!web_kit_view.click(.(控件名字,随机延时最小值,延时最大值,框架名) = 模拟点击控件,\n第一个参数也可以是ele对象,\n随机延时值为可选参数,默认为1,500.\n框架名为可选参数.
!web_kit_view.setEle(.(控件名字,属性值,属性名,框架名) = 更新控件值,成节返回节点,失败返回null空值\n第一个参数也可以是ele对象,\n属性名,框架名为可选参数.\n属性值可以是一个指定多个属性键值对的table对象.
!web_kit_view.select(&控件名字&,__/*输入选项索引,或选项值、选项文本*/) = 查找下拉选框的指定选项,选中并返回选项节点\n第一个参数也可以是ele对象
!web_kit_view.select(&控件名字&,__/*输入选项索引,或选项值、选项文本*/,false) = 查找下拉选框的指定选项,取消选定并返回选项节点\n第一个参数也可以是ele对象
!web_kit_view.getHtml() = 返回网页源码
end intellisense**/
复制代码
示例用法(跟web.form一样)
import win.
import carl.
/*DSG{{*/
var winform = ..win.form(text=&Web Kit&;right=599;bottom=399)
winform.add()
/*}}*/
winform.show();
wb = carl.webkit(winform)
wb.go(&&)
wb.wait();
wb.setEle(&kw&,&aardio&)
wb.click(&su&);//百度一下
win.loopMessage();
完整扩展库下载
(3.29 KB, 下载次数: 342)
10:59 上传
点击文件名下载附件
快手 - 没有做不到的,只有想不到的!
主题帖子积分
这个必须要收藏一下。
这个必须要收藏一下。
主题帖子积分
一级会员, 积分 143, 距离下一级还需 57 积分
一级会员, 积分 143, 距离下一级还需 57 积分
正需要,顶楼主!!!
正需要,顶楼主!!!
主题帖子积分
新手入门, 积分 39, 距离下一级还需 11 积分
新手入门, 积分 39, 距离下一级还需 11 积分
先收藏,以后备用
先收藏,以后备用
主题帖子积分
[quote][size=2][url=forum.php?mod=redirect&goto=findpost&pid=68311&ptid=12646][c
上面的例子,用querySelector就可以实现:
老师,本段代码咋运行提示错误呢
加句 webkit.wait();&
主题帖子积分
[quote][size=2][url=forum.php?mod=redirect&goto=findpost&pid=70253&ptid=12646][c
老师,本段代码咋运行提示错误呢
谢谢!已成功,不错的代码.
主题帖子积分
二级会员, 积分 265, 距离下一级还需 235 积分
二级会员, 积分 265, 距离下一级还需 235 积分
你好 请问你封装的这个 如何实现copy
用你封装的方式wb.copy(eles)没有生效
用form方式wb.execEle(eles,"Copy")
你好 请问你封装的这个 如何实现copy
用你封装的方式wb.copy(eles)没有生效
用form方式wb.execEle(eles,&Copy&)是可以的
主题帖子积分
新手入门, 积分 21, 距离下一级还需 29 积分
新手入门, 积分 21, 距离下一级还需 29 积分
正在学习使用webkit,谢谢carl ,,,
正在学习使用webkit,谢谢carl ,,,
主题帖子积分
一级会员, 积分 60, 距离下一级还需 140 积分
一级会员, 积分 60, 距离下一级还需 140 积分
学习了,收藏
学习了,收藏
主题帖子积分
新手入门, 积分 6, 距离下一级还需 44 积分
新手入门, 积分 6, 距离下一级还需 44 积分
你们有没有遇到这样的问题,用这个WEBKIT开发套用HTML5时,PHP导出电子表格。导不出来,乱码。有什么解决方案吗?
主题帖子积分
二级会员, 积分 309, 距离下一级还需 191 积分
二级会员, 积分 309, 距离下一级还需 191 积分
主题帖子积分
新手入门, 积分 6, 距离下一级还需 44 积分
新手入门, 积分 6, 距离下一级还需 44 积分
Powered by【图文】使用函数封装代码_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
评价文档:
使用函数封装代码
上传于|0|0|文档简介
&&非常有用
大小:131.50KB
登录百度文库,专享文档复制特权,财富值每天免费拿!
你可能喜欢苹果/安卓/wp
学科带头人
学科带头人
积分 3629, 距离下一级还需 2196 积分
权限: 自定义头衔, 签名中使用图片, 隐身, 设置帖子权限, 设置回复可见
道具: 彩虹炫, 涂鸦板, 雷达卡, 热点灯, 金钱卡, 显身卡, 匿名卡, 抢沙发, 提升卡, 沉默卡, 千斤顶下一级可获得
道具: 变色卡
购买后可立即获得
权限: 隐身
道具: 金钱卡, 彩虹炫, 雷达卡, 热点灯, 涂鸦板
TA的文库&&
开心签到天数: 4 天连续签到: 1 天[LV.2]偶尔看看I
本帖最后由 playmore 于
16:00 编辑
就是清除全部变量的函数
rm(list=ls(all=TRUE))
我觉得太长太难记,想把它放到另一个函数里来调用
ClearAll &- function(){
&&rm(list=ls(all=TRUE))
但是上述的办法没有用,应该是函数作用域的问题,在ClearAll函数里调用的rm只能清楚函数内部的变量
有什么办法可以达到清除所有变量,且引用方便的目的呢?谢谢!
载入中......
本帖被以下文库推荐
& |主题: 239, 订阅: 141
& |主题: 22, 订阅: 22
playmore邀请您访问ChinaTeX论坛!!!
清楚所有变量不是很容易的吗? rm(list=ls())
如果你非要他work,那么你可以
ClearAll &- function(){
&&eval(quote(rm(list=ls(all=TRUE))), envir=globalenv())
或者,你想保留你的clear 函数
ClearAll &- function(){
&&eval(quote(rm(list=setdiff(ls(all=TRUE), &ClearAll&))), envir=globalenv())
观点有启发
热心帮助其他会员
总评分:&经验 + 50&
学术水平 + 2&
热心指数 + 1&
信用等级 + 1&
本帖最后由 dxystata 于
04:05 编辑 ntsean 发表于
如果你非要他work,那么你可以
ClearAll &- function(){
&&eval(quote(rm(list=ls(all=TRUE))), envir=globalenv())
或者,你想保留你的clear 函数
ClearAll &- function(){
&&eval(quote(rm(list=setdiff(ls(all=TRUE), &ClearAll&))), envir=globalenv())
}保留clear 函数,什么原理呢?
dxystata 发表于
保留clear 函数,什么原理呢?就是ClearAll 函数还是在global enviroment里面,否则也会被remove掉,如果在global enviroment里面的画
ntsean 发表于
清楚所有变量不是很容易的吗? rm(list=ls())
如果你非要他work,那么你可以多谢指点!
另外,我在rm和ls的帮助里查到的设定全局环境的语句是envir=.GlobalEnv
不知道和你这里的envir=globalenv()有什么区别?
playmore邀请您访问ChinaTeX论坛!!!
初级学术勋章
初级学术勋章
初级热心勋章
初级热心勋章
中级热心勋章
中级热心勋章
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
&nbsp&nbsp|
如有投资本站或合作意向,请联系(010-);
邮箱:service@pinggu.org
投诉或不良信息处理:(010-)
论坛法律顾问:王进律师用C/C++写了几个常用函数,封装在一个类中。
一、头文件【存为:utils.h】
#ifndef _GOOME_COMM_UTILS_H_
#define _GOOME_COMM_UTILS_H_
#include &sys/time.h&
#include &string&
#include &sys/types.h&
#include &sys/stat.h&
#include &unistd.h&
#include &stdio.h&
#include &stdlib.h&
#include &string.h&
#include &vector&
#include &signal.h&
#define MYERRMSG(fmt,args...)& ; printf("[%s中, 第
%d 行 ]; "fmt"\r\n" , __FILE__, __LINE__, ##args);
void*& (* ThreadFunc) (void*);
class CUtils
void& create_pthread(int socket,&
ThreadFunc& threadFunc,& int
nThreadStackSize);
void& connNumInc();
static& void& connNumDec();
static& int&&
getConnNum();
&&static& bool
& findUidFromMap(string& strSimID,
string& strUID);
static& void&&
pushUid2Map(string& strSimID,
string& strUserID);
&&//DDMMYYHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时+8
static& void&
transferTimeStr(char* posTime, char* ownerTimeStr);
&&//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时+8
static& void&
transferTimeStr2(char* posTime, char* ownerTimeStr);
&&//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0&& 小时 不变
static& void&
transferTimeStr3(char* posTime, char* ownerTimeStr);
void& initConnPool(string&
strMysqlIp,& string& strUser,
string&& strPwd,
string& strDbName,& int
nMysqlPort, int nConnNum);
&&& //根据SimID,
取一个用户的UserID 。取到后将 bGetUserId置为 true
static& int&&
getUserIdFromMysql(string& strSimID,
string& strUserID, bool&
bGetUserId)&;&
sendmsg2MQ(string&& sMsg);
void& shutdownMQ();&
static& void& initMQ(
string& strActiveMqIp,& int
nActiveMqPort);
&& static&
void& initMC(
string&& szMemcachedServer, int
getFromMc(string& strKey,&
string& strValue );
setMemcached(string& strKey,&
string& strValue );
static& void& write_file(char*
szContent);
static& void&
write_file_bin(char* pContent, int nLen);
static& void& InitDaemon();
static& void& Hex2Ascii(char*
pSrcHex, int nSrcLen,& char*
pDstAscii);
static& int&&
setPthreadAtrr(pthread_attr_t&&
thread_attr, size_t& stack_set_size);
static& int&&
split(const string& input, const
string& delimiter,
vector&string&&
results, bool includeEmpties);
static& int&&
getFileLen(FILE* fp);
static& string&
getY_M_D_H_M_S();
static& string&
getYMDHMS();
static& string& getY_M_D();
static& string& getYMD();
static& string&
getHH_MM_SS();
static& string&
getHHMMSS();
二、源代码【存为:utils.cpp】
&stdarg.h&
#include &pthread.h&
&activemq/library/ActiveMQCPP.h&
#include &decaf/lang/Thread.h&
&decaf/lang/Runnable.h&
&decaf/util/concurrent/CountDownLatch.h&
#include &decaf/lang/Integer.h&
#include &decaf/util/Date.h&
&activemq/core/ActiveMQConnectionFactory.h&
&activemq/util/Config.h&
#include &cms/Connection.h&
#include &cms/Session.h&
#include &cms/TextMessage.h&
#include &cms/BytesMessage.h&
#include &cms/MapMessage.h&
&libmemcached/memcached.h&
#include "utils.h"
#include "hex2ascii.h"
#include "mutex.h"
#include "configMqMcSql.h"
#include "encapsulation_mysql.h"
#include "connPool.h"
using namespace activemq::
using namespace decaf::util::
using namespace decaf::
using namespace decaf::
using namespace EncapM
g_fp=NULL;
FILE*&& g_fp_bin=NULL;
CMutex& g_mutexWriteF
CMutex& g_mutexWriteFile_B
sConfigMqMcSql&
g_utilConfigMqMcS
CConnPoolV2&
cms::ConnectionFactory*& g_conF
CMutex& g_mutexSimU
map&string, string&
g_nConnNum = 0;
CMutex& g_mutexConnN
void CUtils::create_pthread(int socket,
ThreadFunc& threadFunc ,& int
nThreadStackSize)
&& char tmp[100];
&&int i=0, ret=0;
&&pthread_t&
&&pthread_attr_t&&
CUtils::setPthreadAtrr(pthread_attr,&
nThreadStackSize);//设置栈尺寸
pthread_create(&pid,&
&pthread_attr, threadFunc, (void*)socket);
&&if (ret != 0)
close(socket);
CUtils::connNumDec();
sprintf(tmp,& "Create pthread error [socket: %d ],
close it, cur conn num:%d ***\r\n", socket,
CUtils::getConnNum());
printf(tmp);
CUtils::write_file(tmp
sprintf(tmp, "Create pthread succ! [socket: %d ]\r\n",
socket);&&&&
printf(tmp);
CUtils::write_file(tmp );&&
pthread_detach(pid);&&&
void CUtils::connNumInc()
guard(g_mutexConnNum);
&g_nConnNum++;
void CUtils::connNumDec()
guard(g_mutexConnNum);
&& if(g_nConnNum &
&&g_nConnNum--;
CUtils::getConnNum()
& return g_nConnN
CUtils::findUidFromMap(string& strSimID,
string& strUserID)
& strUserID="00000";
& map&string,
string&::iterator&
guard(g_mutexSimUid);&
& ite = g_sim_uid.find(strSimID);
& if(ite != g_sim_uid.end())
&&& strUserID =
&& printf("get&
[simid:%s,& userid:%s]&
from&& map
succ\n",& strSimID.c_str(),
strUserID.c_str());
CUtils::pushUid2Map(string& strSimID,
string& strUserID)
&&//写本地缓存
guard(g_mutexSimUid);&
&&g_sim_uid[strSimID]
=& strUserID;&
&&printf("[simid:%s,&
userid:%s]& push to& map
succ\n",& strSimID.c_str(),
strUserID.c_str());
//DDMMYYHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void CUtils::transferTimeStr(char* posTime, char*
ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(day, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(year
, posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
&&& int nHour =
(atoi(hour) + 8) % 24;//防止小时大于24
sprintf(hour, "%d", nHour);
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);
//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void& CUtils::transferTimeStr2(char* posTime,
char* ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(year, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(day ,
posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
&&& int nHour =
(atoi(hour) + 8) % 24;//防止小时大于24
sprintf(hour, "%d", nHour);
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);&&
//YYMMDDHHMMSS&
---&&& YYYY-MM-DD
HH:MM:SS.0
void& CUtils::transferTimeStr3(char* posTime,
char* ownerTimeStr)
&& if(!posTime ||
!ownerTimeStr)
&&char year[100],
month[100],day[100], hour[100], minute[100], second[100];
&&char tmp[100];
&&memset(year, 0,
sizeof(year));
&&memset(month , 0, sizeof(month
&&memset(day , 0, sizeof(day
&&memset(hour , 0, sizeof(hour
&&memset(minute , 0,
sizeof(minute ));
&&memset(second , 0,
sizeof(second ));&
&&memcpy(year, posTime, 2);
memcpy(month, posTime+2,
2);&&&&&&&&&
&&& memcpy(day ,
posTime+4,
2);&&&&&&&&&
&&& memcpy(hour
, posTime+6, 2);&
memcpy(minute , posTime+8, 2);&
memcpy(second , posTime+10,
2);&&&&&&&&&&&&
sprintf(ownerTimeStr, "20%s-%s-%s %s:%s:%s.0", year, month,day,
hour,minute,second);&&
void& CUtils::initConnPool(string&
strMysqlIp,& string& strUser,
string&& strPwd,
string& strDbName,& int
nMysqlPort, int nConnNum)
&& char tmp[100];
&& static int&
nCount_ConnPool = 0;
&& if(nCount_ConnPool
int nRet =
g_connPool.Init(strMysqlIp,&&&
strUser,& strPwd,&
strDbName,&&&
nMysqlPort,&& nConnNum);
if(nRet != 0)
sprintf(tmp, "init conn pool fail** \n");
printf(tmp);
CUtils::write_file(tmp);&
&&catch(...)
sprintf(tmp, "init conn pool exception** \n");
printf(tmp);
CUtils::write_file(tmp);&
&& nCount_ConnPool =
//根据SimID, 取一个用户的UserID 。取到后将 bGetUserId置为
CUtils::getUserIdFromMysql(string& strSimID,
string& strUserID, bool&
bGetUserId)
&&char szSQL[1000],
tmp[1000];
&&bGetUserId =
&&CEncapMysql*&
pEM = NULL;
&&&&sprintf(szSQL,
"select sim_id, user_id from& gpsbox.t_user
where& sim_id='%s'", strSimID.c_str());
pEM = (CEncapMysql*)g_connPool.getOneConn();//从连接池借一个连接
if(pEM == NULL)
sprintf(tmp, "get& conn&
from& conn_pool err** \r\n");
printf(tmp);
CUtils::write_file(tmp);&
&&&&&&&&&&
return -1;
//查询,并取到结果集
pEM-&SelectQuery(szSQL);
if(nRet!=0)
g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[%s]SelectQuery& err[nRet=%d]**
\r\n", szSQL, nRet);
printf(tmp);
CUtils::write_file(tmp);&
return -2;
//取一行& &
if( !pEM-&FetchRow())
& g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[mysql] [sim_id:%s& has not
userid**]\r\n",& strSimID.c_str());
printf(tmp);
CUtils::write_file(tmp);&
return -3;
strUserID =
pEM-&GetField("user_id");&
bGetUserId =
g_connPool.retOneConn(pEM); //把连接还给连接池
sprintf(tmp,"[mysql][simid:%s,&
user_id:%s\r\n",&
strSimID.c_str(),strUserID.c_str() );
printf(tmp);
CUtils::write_file(tmp);&&
&&catch(...)
&& g_connPool.retOneConn(pEM);
//把连接还给连接池
sprintf(tmp,"[mysql] [sim_id:%s& , getUserId
FromMysql& exception**]\r\n",&
strSimID.c_str());
printf(tmp);
CUtils::write_file(tmp);
void CUtils::sendmsg2MQ(&
string&& sMsg)
tmp[1000];
Connection* connection =
g_conFactory-&createConnection();
connection-&start();//创建连接
printf("connect activeMQ& succ\r\n");
Session* session =
connection-&createSession(cms::Session::AUTO_ACKNOWLEDGE
//创建线程
TextMessage* message = session-&createTextMessage(
sMsg );//创建消息
Destination*
destination=NULL;
destination = session-&createQueue( "hongyuanQue"
);//创建队列
MessageProducer*
myproducer=session-&createProducer(destination
myproducer-&setDeliveryMode(
DeliveryMode::NON_PERSISTENT );//消息的持久性
myproducer-&send(message );//发送消息
sprintf(tmp, "send [%s] to activeMQ succ\r\n" ,sMsg.c_str()
printf(tmp);
CUtils::write_file(tmp);
session-&close();
connection-&close();
printf("close a connect to&
activeMQ& succ\r\n" );
&& catch(...)
printf("write&
MQ&& exception**\r\n");
void CUtils::shutdownMQ()
activemq::library::ActiveMQCPP::shutdownLibrary();&
void CUtils::initMQ( string&
strActiveMqIp,& int
nActiveMqPort)&
&& static int nCount_InitMQ =
0;//只初始化一次
&& if(nCount_InitMQ
char& szActiveMqServer[100];
sprintf(szActiveMqServer,&
"tcp://%s:%d",&&
strActiveMqIp.c_str(),& nActiveMqPort);
activemq::library::ActiveMQCPP::initializeLibrary();
g_conFactory =&&
cms::ConnectionFactory::createCMSConnectionFactory(
szActiveMqServer );
if(&g_conFactory == NULL)
sprintf(tmp,"Init ActiveMQ fail** \n");
printf(tmp);
CUtils::write_file(tmp);&
nCount_InitMQ = 1;
&& catch(...)
sprintf(tmp,"Init ActiveMQ exception ** \n");
printf(tmp);
CUtils::write_file(tmp);&
exit(0);&&&&
void& CUtils::initMC(
string&& szMemcachedServer, int
& g_utilConfigMqMcSql.m_strMemcachedIp =
szMemcachedS
& g_utilConfigMqMcSql.m_nMemcachedPort =
CUtils::setMemcached(string&
strKey,& string&
strValue& )
&& char tmp[1000];
char& szMemcachedServerIpPort[100];
sprintf(szMemcachedServerIpPort, "%s:%d",&
g_utilConfigMqMcSql.m_strMemcachedIp.c_str() ,
g_utilConfigMqMcSql.m_nMemcachedPort);
&&&&memcached_server_st
* servers = memcached_servers_parse(szMemcachedServerIpPort);
&&&&memcached_st
* memc = memcached_create (NULL);
&&&&memcached_server_push(memc,
&&&&memcached_server_list_free(servers);
&&&&memcached_behavior_set(memc,
MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
&&&&memcached_return
rc = memcached_set(memc, strKey.c_str (), strlen (strKey.c_str ()),
strValue.data (), strValue.size (), 0, 32);
(rc == MEMCACHED_SUCCESS)
sprintf(tmp,"memcached_set succ! \r\n");
printf(tmp);
CUtils::write_file(tmp);&&&&
&&&&&&size_t
ValueLength = 0;
&&&&&&uint32_t
&&&&&&char
* pValue = memcached_get(memc, strKey.c_str (), strlen
(strKey.c_str ()), & ValueLength, &
flags, & rc);
(rc == MEMCACHED_SUCCESS)
&&&&&&&&&&&
sprintf(tmp,"memcached_get succ! [key=%s , value=%s] \r\n",
strKey.c_str (), pValue);
&&&&&&&&&&&
printf(tmp);
CUtils::write_file(tmp);
&&&&&&&&free
&&&&&&else
sprintf(tmp,"memcached_get fail**& [key =%s]
\r\n", strKey.c_str () );
&&&&&&&&&&&&&
printf(tmp);
&&&&&&&&&&
CUtils::write_file(tmp);&
&&&&&&&&free
sprintf(tmp, "memcached_set error**[Key=%s]\r\n",&
strKey.c_str());
printf(tmp);
CUtils::write_file(tmp);&&&&&
&&&&memcached_free(memc);
&&catch(...)
sprintf(tmp, "memcached_set
exception**[Key=%s]\r\n",& strKey.c_str());
printf(tmp);
CUtils::write_file(tmp);&&&&
&&return 0;
int CUtils::getFromMc(string&
strKey,& string& strValue )
char& szMemcachedServerIpPort[100];
sprintf(szMemcachedServerIpPort, "%s:%d",&
g_utilConfigMqMcSql.m_strMemcachedIp.c_str() ,
g_utilConfigMqMcSql.m_nMemcachedPort);
&&memcached_server_st * servers =
memcached_servers_parse(szMemcachedServerIpPort);
&&memcached_st * memc =
memcached_create (NULL);
&&memcached_server_push(memc,
&&memcached_server_list_free(servers);
&&memcached_behavior_set(memc,
MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
ValueLength = 0;
&&memcached_
&&char * pValue =
memcached_get(memc, strKey.c_str (), strlen (strKey.c_str ()),
& ValueLength, & flags,
&&if (rc ==
MEMCACHED_SUCCESS)
&&&&strValue
&&&&printf("memcached_get
key =% s value =% s \r\n", strKey.c_str (),
strValue.c_str());
&&memcached_free(memc);
&&return 0;
//写日志文件
void CUtils::write_file(char* szContent)
guard(g_mutexWriteFile);
& // 先判断文件是否已经打开
& if(g_fp == NULL)
fopen("tmp.dat",
&&&if(g_fp ==
printf("open log file error**\r\n");
& string strT = CUtils::getY_M_D_H_M_S();
& char szTmp[100];
& //先写当前时间
& sprintf(szTmp, "\r\n [%s] ",
&strT.c_str());
& fwrite(szTmp, strlen(szTmp),1, g_fp);
& fwrite(szContent, strlen(szContent),1,
& fflush(g_fp);
//写日志文件【二进制日志】
void CUtils::write_file_bin(char* pContent, int nLen)
guard(g_mutexWriteFile_Bin);
& // 先判断文件是否已经打开&
&& if(g_fp_bin == NULL)
&&&&g_fp_bin
= fopen("bin.dat",
&&&if(g_fp_bin
printf("open g_fp_bin& error**\r\n");
& string strT = CUtils::getY_M_D_H_M_S();
& char szTmp[100];
& //先写当前时间
& sprintf(szTmp, "[%s]",
&strT.c_str());
& fwrite(szTmp, strlen(szTmp),1, g_fp_bin);
& fwrite(pContent, nLen, 1, g_fp_bin);
& fflush(g_fp_bin);
// a function to become a daemon
void CUtils::InitDaemon()
((pid = fork() ) != 0 )
signal( SIGINT,& SIG_IGN);
&&& signal(
SIGHUP,& SIG_IGN);
&&& signal(
SIGPIPE, SIG_IGN);
&&& signal(
SIGTTOU, SIG_IGN);
&&& signal(
SIGTTIN, SIG_IGN);
&&& signal(
SIGCHLD, SIG_IGN);
&&& signal(
SIGTERM, SIG_IGN);
&&& struct
sig.sa_handler = SIG_IGN;
&&& sig.sa_flags
&&& sigemptyset(
&sig.sa_mask);
&&& sigaction(
SIGHUP,&sig,NULL);
((pid = fork() ) != 0 )
setpgrp();
CUtils::Hex2Ascii(char* pSrcHex, int nSrcLen,&
char* pDstAscii)
&& CHex2Ascii&
&& h2a.Hex2Ascii(
pSrcHex,&&
nSrcLen,&& pDstAscii);
CUtils::setPthreadAtrr(pthread_attr_t&&
thread_attr, size_t& stack_set_size)
&& //保护一下
if(stack_set_size& & 16000)
stack_set_size = 16000;
stack_set_size & 70)
stack_set_size = 70;
&&& size_t
status = pthread_attr_init (&thread_attr);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Create attr", status);
return -1;
status = pthread_attr_setdetachstate (
&thread_attr, PTHREAD_CREATE_DETACHED);
(status != 0)
MYERRMSG("%s, [status:%d] \r\n", "Set detach", status);
return -1;
//通常出现的问题之一,下面的宏没有定义
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
//得到当前的线程栈大小
&&& status =
pthread_attr_getstacksize (&thread_attr,
&stack_size);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Get stack size", status);
return -1;
&&& printf
("Default stack size is %u; minimum is
%u\n",&&&&&&
stack_size,& PTHREAD_STACK_MIN);
//设置栈尺寸
&&& status =
pthread_attr_setstacksize (&
&thread_attr, stack_set_size*1024);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Set stack size", status);
return -1;
//得到当前的线程栈的大小
&&& status =
pthread_attr_getstacksize (&thread_attr,
&stack_size);
&&& if (status
MYERRMSG("%s, [status:%d] \r\n", "Get stack size", status);
return -1;
printf ("new& stack size is %u; minimum is
%u\n",&&&&
stack_size, PTHREAD_STACK_MIN);
&&& return
string& CUtils::getY_M_D_H_M_S()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "%d-d-d d:d:d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday,
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
&& return string(szTmp);
CUtils::getYMDHMS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "�dddd", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday,
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
&& return string(szTmp);
string& CUtils::getY_M_D()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "%d-d-d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday );
string(szTmp);
string& CUtils::getYMD()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "�d", pTm-&tm_year + 1900,
pTm-&tm_mon+1, pTm-&tm_mday );
&& return string(szTmp);
string& CUtils::getHH_MM_SS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "d:d:d",&&
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
string(szTmp);&
string& CUtils::getHHMMSS()
time_t& tme = time(NULL);
&&& struct
tm*&& pTm =
localtime(&tme);
szTmp[100];
sprintf(szTmp, "ddd",&&
pTm-&tm_hour, pTm-&tm_min,
pTm-&tm_sec);
string(szTmp);&&
int& CUtils::getFileLen(FILE* fp)
&if(fp == NULL)
&&return -1;
&//获取文件长度
&int iCurPos = ftell(fp);
&fseek(fp,0,SEEK_END);
&int iLen = ftell(fp);
&fseek(fp, iCurPos, SEEK_SET);
& return iL
int CUtils::split(const
string& input, const string&
delimiter,
vector&string&&
results, bool includeEmpties)
&int iPos =
&int newPos =
&int sizeS2 =
(int)delimiter.size();&&
&int isize =
(int)input.size();&&
&if(&( isize == 0
)&||&( sizeS2 == 0
&vector&int&
&newPos = input.find (delimiter,
&if( newPos & 0
&&return 0;
&int numFound =
&while( newPos &= iPos
&&numFound++;&&&positions.push_back(newPos);&&&iPos
&&newPos = input.find (delimiter,
iPos+sizeS2);&&
&if( numFound == 0
)&&{&&&return
&for( int i=0; i &=
(int)positions.size(); ++i
&&if( i == 0 )
input.substr( i, positions[i] );
&&int offset = positions[i-1] +
sizeS2;&&&
&&if( offset &
isize )&&&
&&&if( i ==
positions.size()
input.substr(offset);&&&&
&&&else if( i
= input.substr( positions[i-1] + sizeS2, positions[i] -
positions[i-1] - sizeS2 );&
&&if( includeEmpties || (
s.size() & 0 )
&&&results.push_back(s);&&
&return numF&
三、Hex2Ascii.h文件内容
__HEX_TO_ASCII__
#define& __HEX_TO_ASCII__
class& CHex2Ascii
&&CHex2Ascii(){}
&&~CHex2Ascii(){}
&&& //0~9 转为
‘0’~‘9’&&& 10~15
转为 ‘a’~'f'
char& GetAscii(int& n);
//一个字节(16进制)转为2个Ascii字符【一个十六进制的字节,如 0xa7, 高四位是
10,& 低四位是 7, 然后转为 'a'& '7'】
One2Two(char chSrc, char* pDst);
//将16进制转为可显示的 ASCII串,如 0xAA 0xBB 0x8C& 转为ASCII串
“AA BB 8C”
void& Hex2Ascii(char* pSrcHex, int
nSrcLen,& char* pDstAscii);
四、Hex2Ascii.cpp文件内容&
#include &stdlib.h&
#include "hex2ascii.h"
//0~9 转为
‘0’~‘9’&&& 10~15
转为 ‘a’~'f'
char& CHex2Ascii::GetAscii(int&
return& '0' +
&& else if( n&=
return& 'a' + n-10;
&&& return
//一个字节(16进制)转为2个Ascii字符【一个十六进制的字节,如 0xa7,
高四位是 10,& 低四位是 7, 然后转为 'a'&
void CHex2Ascii::One2Two(char chSrc, char* pDst)
&& char& chHigh
= (chSrc && 4)&
&& pDst[0] =
GetAscii(chHigh);
chLow& = (chSrc&0x0f);
&& pDst[1] =
GetAscii(chLow);
//将16进制转为 可显示的 ASCII串,如 0xAA 0xBB
0x8C& 转为ASCII串 “AA BB 8C”
void& CHex2Ascii::Hex2Ascii(char* pSrcHex, int
nSrcLen,& char* pDstAscii)
& if(!pSrcHex || !pDstAscii)
& char pTmp[2];
& for(int i=0; i&nSrcL
&&&One2Two(pSrcHex[i],
&&&pDstAscii[i*3+0]
= pTmp[0];
&&&pDstAscii[i*3+1]
= pTmp[1];
&&&pDstAscii[i*3+2]
&&&pDstAscii[i*3+3]
&五、connPool.h内容如下:
#ifndef __CONNECTION_POOL_H__
#define __CONNECTION_POOL_H__
#include "mutex.h"
MYSQL_CONN_NUM_MAX_VALUE&&
enum _USE_STATUS
&& US_USE = 0,
&& US_IDLE = 1
typedef& struct
_sConStatus
class CConnPool
CConnPool();
~CConnPool();
Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum);//connection& pool
getOneConn();//get a connection
void& retOneConn(void* pMysql);// return a
connection
void& checkConn(); // check the connection if is
createOneConn();
m_szMysqlIp[100];
&& char m_szUser[100];
&& char m_szPwd[100];
&& char m_szDbName[100];
m_nMysqlP&&
CMutex& m_sM
vector&void*&&
map&void*, int& m_mapVI;
map&void*, void*&
m_mapMysqlS
class CConnPoolV2
CConnPoolV2();
~CConnPoolV2();
Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum);//connection& pool
getOneConn(); //从连接池取一个连接
void& retOneConn(void* pConn);//
连接用完了,把它放回连接池。以便其他人用。
void& checkConn(); // check the connection if is
createOneConn();
&& string m_strMysqlIp;
&& string m_strU
&& string m_strP
&& string m_strDbN
m_nMysqlP&
CMutex& m_sM
vector&void*&&
map&void*, int& m_mapVI;
//& 从连接的地址,快速找到索引,便于存放到m_vectorConn中。
六、connPool.cpp内容如下:
#include &stdlib.h&
#include &errno.h&
#include &string.h&
#include &sys/types.h&
#include &netinet/in.h&
#include &sys/socket.h&
#include &sys/wait.h&
#include &arpa/inet.h&
#include &unistd.h&
#include &fcntl.h&
#include &pthread.h&
&iostream&&&&&&&&&&&&&&&&&&&&&&&
#include &memory&
#include &string&
#include &map&
#include &vector&
#include "mysql.h"
#include "encapsulation_mysql.h"
#include "connPool.h"
#include "mutex.h"
using namespace EncapM
CConnPool::CConnPool( )
CConnPool::~CConnPool( )
void* CConnPool::createOneConn()
mysql = mysql_init(0);
if(mysql == NULL)
&& "mysql_init fail**"
&&&&return
if(mysql_real_connect(mysql,& m_szMysqlIp ,
m_szUser ,&&
m_szPwd,&&&
m_szDbName& ,& m_nMysqlPort,
NULL,0)==NULL)
&& "connect failure!"
&&&&&return
&& "connect success!"
CConnPool::Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum)
strcpy(m_szMysqlIp, strMysqlIp.c_str());
&&& strcpy(
m_szUser, strUser.c_str());
strcpy(m_szPwd, strPwd.c_str());
strcpy(m_szDbName, strDbName.c_str());
&&& m_nMysqlPort
= nMysqlP&&
&& m_nConnNum =
&&& for(int i=0;
i&nConnN i++)
&& mysql =
(MYSQL*)this-&createOneConn();
&& if(mysql == NULL)
&& &return
sConStatus* scs = new sConStatus();
scs-&connAddr =
scs-&useStatus = US_IDLE;
m_vectorConn.push_back(scs);&
m_mapVI[scs] =
m_mapMysqlScs[mysql] =
&&m_nConnNum = nConnN
void* CConnPool::getOneConn()
&&& int N =
m_vectorConn.size();
&&for(int i=0; i&
CGuard& guard(m_sMutex);
sConStatus* scs = (sConStatus*)m_vectorConn[i];
if(scs-&useStatus ==&
&&&&&&&&&&
scs-&useStatus = US_USE;
scs-&connA
&&return NULL;
CConnPool::retOneConn(void* pMysql)
& map&void*,
void*&::iterator& it1;
& map&void*,
int&::iterator it2;
& CGuard& guard(m_sMutex);
& it1 = m_mapMysqlScs.find(pMysql);
& if(it1 == m_mapMysqlScs.end())
m_mapVI.find(it1-&second);
& if(it2 == m_mapVI.end())
& int nInx =
& sConStatus* scs =
(sConStatus*) m_vectorConn[nInx];
& scs-&useStatus = US_IDLE;
CConnPool::checkConn()
&& map&void*,
void*&::iterator& it1;
&& MYSQL*&
&& &for(int i=0;
i&m_nConnN i++)
CGuard& guard(m_sMutex);
&& & sConStatus*
scs = (sConStatus*)m_vectorConn[i];
if(scs-&useStatus == US_USE)
&& & mysql
=(MYSQL*)(scs-&connAddr);
status=mysql_query(mysql, "select count(*) from t_" );
&&& if(status !=
0) //说明连接已经不可用了。
it1 = m_mapMysqlScs.find(mysql);
if(it1 != m_mapMysqlScs.end())
m_mapMysqlScs.erase(it1);
mysql_close(mysql);
mysql = (MYSQL*)this-&createOneConn();
m_mapMysqlScs[mysql] =
////////////////////////////// ,
这个类这样写,感觉耦合性更为松散,比较好。使用起来也好理解一些。
CConnPoolV2::CConnPoolV2( )
CConnPoolV2::~CConnPoolV2( )
//创建一个连接,并设为 IDLE状态。
void* CConnPoolV2::createOneConn()
CEncapMysql*& pEM = new CEncapMysql();
if(pEM == NULL)
&printf("pEM ==
NULL**\r\n");&
&return NULL;
int nRet = pEM-&Connect(m_strMysqlIp.c_str(),
m_strUser.c_str(), m_strPwd.c_str());
if(nRet != 0)
&printf("pEM-&Connect
fail**\r\n");&
&return NULL;
pEM-&SetIdle();
return pEM;
&&catch(...)
printf("createOneConn&
exception**\r\n");&
return NULL;
//成功: 返回0
int CConnPoolV2::Init(string& strMysqlIp,
string&& strUser,
string&& strPwd,
string&& strDbName, int
nMysqlPort, int nConnNum)
m_strMysqlIp& = strMysqlIp;
m_strUser&&&&
m_strPwd&&&&&
m_strDbName&& = strDbN
&&& m_nMysqlPort
= nMysqlP&&
&& m_nConnNum =
&&& CEncapMysql*
&&& for(int i=0;
i&nConnN i++)
(CEncapMysql*)this-&createOneConn();
& return -1;
m_vectorConn.push_back(pEM);&
m_mapVI[pEM] =
void* CConnPoolV2::getOneConn()
CGuard& guard(m_sMutex);
&&for(int i=0; i&
m_nConnN i++)
CEncapMysql* pEM = (CEncapMysql*)m_vectorConn[i];
if( pEM-&IsIdle())
&&&&&&&&&&
pEM-&SetUsed();
& return pEM;
&&//可能访问MYSQL的用户较多,连接池中已无空闲连接了。只要总连接数没有超限,就新建一个连接。
&&if(m_nConnNum &
MYSQL_CONN_NUM_MAX_VALUE)
CEncapMysql* pEM =
(CEncapMysql*)this-&createOneConn();
& return NULL;
m_vectorConn.push_back(pEM);&
m_mapVI[pEM] = m_nConnNum++;
&&return NULL;
CConnPoolV2::retOneConn(void* pConn)
& map&void*,
guard(m_sMutex);
m_mapVI.find(pConn);
& if(it == m_mapVI.end())
& int nInx = it-&
& CEncapMysql* pEM =
(CEncapMysql*) m_vectorConn[nInx];
& pEM-&SetIdle();
CConnPoolV2::checkConn()
&//暂时可以不实现。因为查询失败时,已重新连接了。
&七、mutex.h的内容如下:
#ifndef _MUTEX_H_
#define _MUTEX_H_
#include &stdlib.h&
#include &string.h&
#include &pthread.h&
#include &iostream&
class CMutex
CMutex() ;
~CMutex() ;
int Lock();
int TryLock();
int UnLock();
pthread_mutex_t &getMutexRef();
& protected:
pthread_mutex_t& m_sM
class CGuard
CGuard(CMutex &mutex);
~CGuard();
&&& CMutex
class CCondition
CCondition();
~CCondition();
wait(CMutex &mutex);
pthread_cond_t m_
///////////////////////////////////////////
class CLock
CLock(){};
&&& virtual
~CLock(){};
//互斥锁: 线程阻塞, 直到获取锁资源. 失败返回-1. 如果不是互斥锁类型,直接返回
&&& virtual int
lock() = 0;
&&& //互斥锁: 释放锁.
失败返回-1. 如果不是互斥锁类型,直接返回
&&& virtual int
unlock() = 0;
&&& //读写锁:
获取读锁资源. 失败返回-1. 如果锁类型不支持读写锁,直接返回.
&&& virtual int
rdlock() = 0;
&&& //读写锁:
获取写锁资源. 失败返回-1. 如果锁类型不支持读写锁,直接返回.
&&& virtual int
wrlock() = 0;
class CMutexLock
CMutexLock(pthread_mutexattr_t* pAttr = NULL);
~CMutexLock();
//互斥锁: 线程阻塞, 直到获取锁资源. 失败返回-1.
return pthread_mutex_lock(&m_lock);
&&& //互斥锁: 释放锁.
失败返回-1
return pthread_mutex_unlock(&m_lock);
&&& //读写锁的方法,
这里只是保持适配
return -1;
&&& //读写锁的方法,
这里只是保持适配
return -1;
pthread_mutex_t& getLock()
pthread_mutex_t& m_
&&& CMutexLock
(const CMutexLock &); //不让拷贝
operator= (const CMutexLock &); //不让赋值
class CRWLock
CRWLock(pthread_rwlockattr_t* pAttr = NULL);
~CRWLock();
//互斥锁的方法, 这里只是保持适配
return -1;
//释放锁资源
return pthread_rwlock_unlock(&m_lock);
&&& //获取读锁资源.
失败返回-1.
return pthread_rwlock_rdlock(&m_lock);
&&& //获取写锁资源.
失败返回-1.
return pthread_rwlock_wrlock(&m_lock);
pthread_rwlock_t& m_
&&& CRWLock
(const CRWLock &); //不让拷贝
operator= (const CRWLock &); //不让赋值
template&typename CLock =
CMutexLock&
class CMutexGuard
CMutexGuard(CLock &lock) : m_lock(lock)
m_lock.lock();
~CMutexGuard()
m_lock.unlock();
protected:
&m_ //引用: 锁
&&& CMutexGuard
(const CMutexGuard&CLock&
&); //不让拷贝构造
operator= (const
CMutexGuard&CLock&&
&); //不让赋值
template&typename CLock =
class CReadGuard : public
CMutexGuard&CRWLock&
&&& //重写构造和析构,
使用读写锁实现
CReadGuard(CLock &rwlock) :
CMutexGuard&CRWLock&(rwlock)
m_lock.rdlock();
~CReadGuard()
m_lock.unlock();
template&typename CLock =
class CWriteGuard : public
CMutexGuard&CRWLock&
&&& //重写构造和析构,
使用读写锁实现
CWriteGuard(CLock &rwlock) :
CMutexGuard&CRWLock&(rwlock)
m_lock.wrlock();
~CWriteGuard()
m_lock.unlock();
八、mutex.cpp的内容如下:
&pthread.h&
#include "mutex.h"
CMutex::CMutex()
& pthread_mutexattr_t& l_sAttr
pthread_mutexattr_init(&l_sAttr);
pthread_mutex_init(&m_sMutex,&l_sAttr);
pthread_mutexattr_destroy(&l_sAttr);
CMutex::~CMutex()
pthread_mutex_destroy(&m_sMutex);
int CMutex::Lock()
return(pthread_mutex_lock(&m_sMutex));
int CMutex::TryLock()
return(pthread_mutex_trylock(&m_sMutex));
int CMutex::UnLock()
return(pthread_mutex_unlock(&m_sMutex));
pthread_mutex_t
&CMutex::getMutexRef()
&&& return
//CGuard实现部分
CGuard::CGuard(CMutex &mutex)
: m_mutex(mutex)
m_mutex.Lock();
CGuard::~CGuard()
m_mutex.UnLock();
//CCondition实现部分
CCondition::CCondition()
pthread_condattr_
pthread_condattr_init(&attr);
pthread_cond_init(&m_cond,
pthread_condattr_destroy(&attr);
CCondition::~CCondition()
pthread_cond_destroy(&m_cond);
int CCondition::wait(CMutex
&&& return
pthread_cond_wait(&m_cond,
&mutex.getMutexRef());
int CCondition::signal()
&&& return
pthread_cond_signal(&m_cond);
CMutexLock::CMutexLock(pthread_mutexattr_t* pAttr )
pthread_mutexattr_init(pAttr);
pthread_mutex_init(&m_lock, pAttr);
pthread_mutexattr_destroy(pAttr);
pthread_mutex_init(&m_lock, NULL);
CMutexLock::~CMutexLock()
pthread_mutex_destroy(&m_lock);
CRWLock::CRWLock(pthread_rwlockattr_t* pAttr )
pthread_rwlockattr_init(pAttr);
pthread_rwlock_init(&m_lock, pAttr);
pthread_rwlockattr_destroy(pAttr);
pthread_rwlock_init(&m_lock, pAttr);
CRWLock::~CRWLock()
pthread_rwlock_destroy(&m_lock);
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 函数怎么写输入 的文章

 

随机推荐