Mars - 微信官方的跨平臺跨業務的終端基礎組件

zhsuppervi 7年前發布 | 12K 次閱讀 安卓開發 移動開發

Mars

Mars is a cross-platform infrastructure component developed by WeChat Mobile Team.

  • comm:common library, including socket, thread, message queue, coroutine, etc.
  • xlog:a reliable log component with high-performance.
  • SDT: a network detection component.
  • STN: a signalling network component, the major part of Mars.

Samples

Start with sample usagehere

Getting started

ChooseAndroidoriOS/OS X

Android

You can use eithermars-wrapperormars-core. We recommend you to use mars-wrapper if only sample is needed, while mars-core is preferred to be used in your app.

mars-wrapper

Add dependencies by adding the following lines to your app/build.gradle.

dependencies {
    compile 'com.tencent.mars:mars-wrapper:1.1.3'
}

OR

mars-core

Add dependencies by adding the following lines to your app/build.gradle.

dependencies {
    compile 'com.tencent.mars:mars-core:1.1.3'
}

If you read here, make sure you have added dependencies of mars-wrapper or mars-core.

Xlog Init

Initialize Xlog when your app starts. Remember to use an exclusive folder to save the log files, no other files is acceptable in the folder since they would be removed by the cleansing function in Xlog automatically.

When multiple processes is used in your app, make sure that each process owns its exclusive log file.

System.loadLibrary("stlport_shared");
System.loadLibrary("marsxlog");

final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath(); final String logPath = SDCARD + "/marssample/log";

//init xlog if (BuildConfig.DEBUG) { Xlog.appenderOpen(Xlog.LEVEL_DEBUG, Xlog.AppednerModeAsync, "", logPath, "MarsSample"); Xlog.setConsoleLogOpen(true);

} else { Xlog.appenderOpen(Xlog.LEVEL_INFO, Xlog.AppednerModeAsync, "", logPath, "MarsSample"); Xlog.setConsoleLogOpen(false); }

Log.setLogImp(new Xlog());</code></pre>

Uninitialized Xlog when your app exits

Log.appenderClose();

STN Init

If you add dependencies of mars-core to your project, you need initialize and uninitialized STN.

Initialize STN before you use it

// set callback
AppLogic.setCallBack(stub);
StnLogic.setCallBack(stub);
SdtLogic.setCallBack(stub);

// Initialize the Mars PlatformComm Mars.init(getApplicationContext(), new Handler(Looper.getMainLooper()));

// Initialize the Mars StnLogic.setLonglinkSvrAddr(profile.longLinkHost(), profile.longLinkPorts()); StnLogic.setShortlinkSvrAddr(profile.shortLinkPort()); StnLogic.setClientVersion(profile.productID()); Mars.onCreate(true);

BaseEvent.onForeground(true); StnLogic.makesureLongLinkConnected();</code></pre>

Firstly, you should call the setCallBack interface, and secondly, the Mars.init. Then, to initialize the Mars, there is to need to strictly follow the orders of the four commands. Finally, after Mars are initialized, onForeground and makesureLongLinkConnect can be called.

Destroy STN or exit your app:

Mars.onDestroy();

Event Change

Network change:

BaseEvent.onNetworkChange()

If you add dependencies of mars-wrapper to your project, you just need initialize STN and no need uninitialized.

MarsServiceProxy.init(this, getMainLooper(),null);

No matter which way of dependencies you used, you must pay attention to these.

The state (background or foreground) of app is changed:

BaseEvent.onForeground(boolean);

The account of app is changed:

StnLogic.reset();

If you want to modify the encryption algorithm of Xlog, the packer/unpacker of longlink/shortlink, or you want to define the other components by yourself, referhere

iOS/OS X

Compile

python build_apple.py

Add mars.framework as a dependency of your project.

Xlog Init

Initialize Xlog when your app starts. Remember to use an exclusive folder to save the log files, no other files is acceptable in the folder since they would be removed by the cleansing function in Xlog automatically.

NSString* logPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/log"];

// set do not backup for logpath const char* attrName = "com.apple.MobileBackup"; u_int8_t attrValue = 1; setxattr([logPath UTF8String], attrName, &attrValue, sizeof(attrValue), 0, 0);

// init xlogger

if DEBUG

xlogger_SetLevel(kLevelDebug); appender_set_console_log(true);

else

xlogger_SetLevel(kLevelInfo); appender_set_console_log(false);

endif

appender_open(kAppednerAsync, [logPath UTF8String], "Test");</code></pre>

Uninitialized xlog in function "applicationWillTerminate"

appender_close();

STN Init

Initialize STN before you use it:

- (void)setCallBack {
    mars::stn::SetCallback(mars::stn::StnCallBack::Instance());
    mars::app::SetCallback(mars::app::AppCallBack::Instance());
}

  • (void) createMars { mars::baseevent::OnCreate(); }

  • (void)setClientVersion:(UInt32)clientVersion { mars::stn::SetClientVersion(clientVersion); }

  • (void)setShortLinkDebugIP:(NSString *)IP port:(const unsigned short)port { std::string ipAddress([IP UTF8String]); mars::stn::SetShortlinkSvrAddr(port, ipAddress); }

  • (void)setShortLinkPort:(const unsigned short)port { mars::stn::SetShortlinkSvrAddr(port); }

  • (void)setLongLinkAddress:(NSString )string port:(const unsigned short)port debugIP:(NSString )IP { std::string ipAddress([string UTF8String]); std::string debugIP([IP UTF8String]); std::vector<uint16_t> ports; ports.push_back(port); mars::stn::SetLonglinkSvrAddr(ipAddress,ports,debugIP); }

  • (void)setLongLinkAddress:(NSString *)string port:(const unsigned short)port { std::string ipAddress([string UTF8String]); std::vector<uint16_t> ports; ports.push_back(port); mars::stn::SetLonglinkSvrAddr(ipAddress,ports); }

  • (void)reportEvent_OnForeground:(BOOL)isForeground { mars::baseevent::OnForeground(isForground); }

  • (void)makesureLongLinkConnect { mars::stn::MakesureLonglinkConnected(); }</code></pre>

    Firstly, you should call the setCalBack interface, and secondly, the Mars.init. Then, to initialize the Mars, there is to need to strictly follow the orders of the four commands. Finally, after Mars are initialized, onForeground and makesureLongLinkConnect can be called.

    If you want to destroy STN or exit App:

    - (void)destroyMars {
      mars::baseevent::OnDestroy();
    }

    Event Change

    When the App's state of background or foreground is changed:

    - (void)reportEvent_OnForeground:(BOOL)isForeground {
      mars::baseevent::OnForeground(isForground);
    }

    Network change:

    - (void)reportEvent_OnNetworkChange {
      mars::baseevent::OnNetworkChange();
    }

    Support

    Any problem?

    1. Learn more frommars/sample.
    2. Read thesource code.
    3. Read thewiki orFAQ for help.
    4. Contact us for help.

    Contributing

    For more information about contributing issues or pull requests, see our Mars Contributing Guide .

    License

    Mars is under the MIT license. See theLICENSE file for details.

    Mars

    Mars 是微信官方的跨平臺跨業務的終端基礎組件。

    Mars - 微信官方的跨平臺跨業務的終端基礎組件

    • comm:可以獨立使用的公共庫,包括 socket、線程、消息隊列、協程等;
    • xlog:高可靠性高性能的運行期日志組件;
    • SDT: 網絡診斷組件;
    • STN: 信令分發網絡模塊,也是 Mars 最主要的部分。

    Samples

    sample 的使用請參考這里

    Getting started

    接入Android或者iOS/OS X

    gradle 接入我們提供了兩種接入方式:mars-wrapper或者mars-core。如果你只是想做個 sample 推薦使用 mars-wrapper,可以快速開發;但是如果你想把 mars 用到你的 app 中的話,推薦使用 mars-core,可定制性更高。

    mars-wrapper

    在 app/build.gradle 中添加 mars-wrapper 的依賴:

    dependencies {
      compile 'com.tencent.mars:mars-wrapper:1.1.3'
    }

    或者

    mars-core

    在 app/build.gradle 中添加 mars-core 的依賴:

    dependencies {
      compile 'com.tencent.mars:mars-core:1.1.3'
    }

    接著往下操作之前,請先確保你已經添加了 mars-wrapper 或者 mars-core 的依賴

    Xlog Init

    在程序啟動加載 Xlog 后緊接著初始化 Xlog。但要注意如果你的程序使用了多進程,不要把多個進程的日志輸出到同一個文件中,保證每個進程獨享一個日志文件。而且保存 log 的目錄請使用單獨的目錄,不要存放任何其他文件防止被 xlog 自動清理功能誤刪。

    System.loadLibrary("stlport_shared");
    System.loadLibrary("marsxlog");

final String SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath(); final String logPath = SDCARD + "/marssample/log";

//init xlog if (BuildConfig.DEBUG) { Xlog.appenderOpen(Xlog.LEVEL_DEBUG, Xlog.AppednerModeAsync, "", logPath, "MarsSample"); Xlog.setConsoleLogOpen(true);

} else { Xlog.appenderOpen(Xlog.LEVEL_INFO, Xlog.AppednerModeAsync, "", logPath, "MarsSample"); Xlog.setConsoleLogOpen(false); }

Log.setLogImp(new Xlog());</code></pre>

程序退出時關閉日志:

Log.appenderClose();

STN Init

如果你是把 mars-core 作為依賴加入到你的項目中的話,你需要顯式的初始化和反初始化 STN

在使用 STN 之前進行初始化

// set callback
AppLogic.setCallBack(stub);
StnLogic.setCallBack(stub);
SdtLogic.setCallBack(stub);

// Initialize the Mars PlatformComm Mars.init(getApplicationContext(), new Handler(Looper.getMainLooper()));

// Initialize the Mars StnLogic.setLonglinkSvrAddr(profile.longLinkHost(), profile.longLinkPorts()); StnLogic.setShortlinkSvrAddr(profile.shortLinkPort()); StnLogic.setClientVersion(profile.productID()); Mars.onCreate(true); BaseEvent.onForeground(true);

StnLogic.makesureLongLinkConnected();</code></pre>

初始化順序不一定要嚴格遵守上述代碼的順序,但在初始化時首先要調用 setCallBack 接口 (callback 文件的編寫可以參考 demo),再調用 Mars.init,最后再調用onForeground 和 makesureLongLinkConnect,中間順序可以隨意更改。 注意:STN 默認是后臺,所以初始化 STN 后需要主動調用一次 BaseEvent.onForeground(true)

需要釋放 STN 或者退出程序時:

Mars.onDestroy();

Event Change

網絡切換時:

BaseEvent.onNetworkChange()

如果你是把 mars-wrapper 作為依賴加入到你的項目中,你只需要顯式的初始化 STN,不需要反初始化(因為 mars-wrapper 會進行反初始化)

MarsServiceProxy.init(this, getMainLooper(),null);

不管你是使用 mars-wrapper 還是 mars-core,你都需要特別注意以下事件:

前后臺切換:

BaseEvent.onForeground(boolean);

應用的賬號信息更改:

StnLogic.reset();

編譯

python build_apple.py

把 mars.framework 作為依賴加入到你的項目中

Xlog Init

在程序啟動加載 Xlog 后緊接著初始化 Xlog。但要注意保存 log 的目錄請使用單獨的目錄,不要存放任何其他文件防止被 xlog 自動清理功能誤刪。

NSString* logPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/log"];

// set do not backup for logpath const char* attrName = "com.apple.MobileBackup"; u_int8_t attrValue = 1; setxattr([logPath UTF8String], attrName, &attrValue, sizeof(attrValue), 0, 0);

// init xlogger

if DEBUG

xlogger_SetLevel(kLevelDebug); appender_set_console_log(true);

else

xlogger_SetLevel(kLevelInfo); appender_set_console_log(false);

endif

appender_open(kAppednerAsync, [logPath UTF8String], "Test");</code></pre>

在函數 "applicationWillTerminate" 中反初始化 Xlog

appender_close();

STN Init

在你用 STN 之前初始化:

- (void)setCallBack {
    mars::stn::SetCallback(mars::stn::StnCallBack::Instance());
    mars::app::SetCallback(mars::app::AppCallBack::Instance());
}

  • (void) createMars { mars::baseevent::OnCreate(); }

  • (void)setClientVersion:(UInt32)clientVersion { mars::stn::SetClientVersion(clientVersion); }

  • (void)setShortLinkDebugIP:(NSString *)IP port:(const unsigned short)port { std::string ipAddress([IP UTF8String]); mars::stn::SetShortlinkSvrAddr(port, ipAddress); }

  • (void)setShortLinkPort:(const unsigned short)port { mars::stn::SetShortlinkSvrAddr(port); }

  • (void)setLongLinkAddress:(NSString )string port:(const unsigned short)port debugIP:(NSString )IP { std::string ipAddress([string UTF8String]); std::string debugIP([IP UTF8String]); std::vector<uint16_t> ports; ports.push_back(port); mars::stn::SetLonglinkSvrAddr(ipAddress,ports,debugIP); }

  • (void)setLongLinkAddress:(NSString *)string port:(const unsigned short)port { std::string ipAddress([string UTF8String]); std::vector<uint16_t> ports; ports.push_back(port); mars::stn::SetLonglinkSvrAddr(ipAddress,ports); }

  • (void)reportEvent_OnForeground:(BOOL)isForeground { mars::baseevent::OnForeground(isForground); }

  • (void)makesureLongLinkConnect { mars::stn::MakesureLonglinkConnected(); }</code></pre>

    初始化順序不一定要嚴格遵守上述代碼的順序,但在初始化時首先要調用 setCallBack 接口 (callback 文件的編寫可以參考 demo),再調用 Mars.init,最后再調用 onForeground 和 makesureLongLinkConnect,中間順序可以隨意更改。 注意:STN 默認是后臺,所以初始化 STN 后需要主動調用一次 BaseEvent.onForeground(true)

    需要釋放 STN 或者退出程序時:

    - (void)destroyMars {
      mars::baseevent::OnDestroy();
    }

    Event Change

    前后臺切換時:

    - (void)reportEvent_OnForeground:(BOOL)isForeground {
      mars::baseevent::OnForeground(isForeground);
    }

    網絡切換時:

    - (void)reportEvent_OnNetworkChange {
      mars::baseevent::OnNetworkChange();
    }

    Support

    還有其他問題?

    1. 參看mars/sample.
    2. 閱讀源碼.
    3. 閱讀wiki 或者FAQ
    4. 聯系我們.

    Contributing

    關于 Mars 分支管理、issue 以及 pr 規范,

     

     

 本文由用戶 zhsuppervi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!