2013年9月18日 星期三

MongoDB 簡介、常用指令


mongodb由C++寫就,其名字來自humongous這個單詞的中間部分,從名字可見其野心所在就是海量資料的處理。關於它的一個最簡潔描述為:scalable, high-performance, open source, schema-free, document-oriented database。MongoDB的主要目標是在鍵/值存儲方式(提供了高性能和高度伸縮性)以及傳統的RDBMS系統(豐富的功能)架起一座橋樑,集兩者的優勢於一身。



一些概念
一個mongod服務可以有建立多個資料庫,每個資料庫可以有多張表,這裡的表名叫collection,每個collection可以存放多個文檔(document),每個文檔都以BSON(binary json)的形式存放於硬碟中,因此可以存儲比較複雜的資料類型。它是以單文檔為單位存儲的,你可以任意給一個或一批文檔新增或刪除欄位,而不會對其它文檔造成影響,這就是所謂的schema-free,這也是文檔型資料庫最主要的優點。跟一般的key-value資料庫不一樣的是,它的value中存儲了結構資訊,所以你又可以像關係型數據庫那樣對某些域進行讀寫、統計等操作。Mongo最大的特點是他支援的查詢語言非常強大,其語法有點類似於物件導向的查詢語言,幾乎可以實現類似關聯式資料庫單表查詢的絕大部分功能,而且還支援對資料建立索引。Mongo還可以解決海量資料的查詢效率,根據官方文檔,當資料量達到50GB以上資料時,Mongo資料庫存取速度是MySQL10 倍以上。

BSON
BSON是Binary JSON 的簡稱,是一個JSON文檔物件的二進位編碼格式。BSON同JSON一樣支援往其它文檔物件和陣列中再插入文檔物件和陣列,同時擴展了JSON的資料類型。如:BSON有Date類型和BinDate類型。
BSON被比作二進位的交換格式,如同Protocol Buffers,但BSON比它更“schema-less”,非常好的靈活性但空間佔用稍微大一點。

BSON有以下三個特點:
1.  羽量級
2.  跨平臺
3.  效率高



shell操作資料庫:

   1.  超級用戶相關:
         1. #進入資料庫admin
use admin
         2. #增加或修改使用者密碼
          db.addUser('name','pwd')
         3. #查看用戶列表
          db.system.users.find()
         4. #用戶認證
          db.auth('name','pwd')
         5. #刪除用戶
          db.removeUser('name')
         6. #查看所有用戶
          show users
         7. #查看所有資料庫
          show dbs
         8. #查看所有的collection
          show collections
         9. #查看各collection的狀態
          db.printCollectionStats()
        10. #查看主從複製狀態
          db.printReplicationInfo()
        11. #修復資料庫
          db.repairDatabase()
        12. #設置記錄profiling,0=off 1=slow 2=all
          db.setProfilingLevel(1)
        13. #查看profiling
          show profile
        14. #拷貝資料庫
          db.copyDatabase('mail_addr','mail_addr_tmp')
        15. #刪除collection
          db.mail_addr.drop()
        16. #刪除當前的資料庫
          db.dropDatabase()
       
   2. 增刪改
         1. #存儲嵌套的物件
db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

         2. #存儲陣列物件
db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

         3. #根據query條件修改,如果不存在則插入,允許修改多條記錄
            db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
         4. #刪除yy=5的記錄
            db.foo.remove({'yy':5})
         5. #刪除所有的記錄
            db.foo.remove()

   3. 索引
         1. #增加索引:1(ascending),-1(descending)
         2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
         3. #索引子物件
         4. db.user_addr.ensureIndex({'Al.Em': 1})
         5. #查看索引資訊
         6. db.foo.getIndexes()
         7. db.foo.getIndexKeys()
         8. #根據索引名刪除索引
         9. db.user_addr.dropIndex('Al.Em_1')

   4. 查詢
         1. #查找所有
        2. db.foo.find()
        3. #查找一條記錄
        4. db.foo.findOne()
        5. #根據條件檢索10條記錄
        6. db.foo.find({'msg':'Hello 1'}).limit(10)
        7. #sort排序
        8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})
         9. db.deliver_status.find().sort({'Ct':-1}).limit(1)
        10. #count操作
        11. db.user_addr.count()
        12. #distinct操作,查詢指定列,去重複
        13. db.foo.distinct('msg')
        14. #”>=”操作
        15. db.foo.find({"timestamp": {"$gte" : 2}})
        16. #子物件的查找
        17. db.foo.find({'address.city':'beijing'})


mongod.exe -dbpath XX/XXX/XX

JAVA Socket

SocketSever

import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer extends java.lang.Thread{
   private boolean OutServer = false;
   private ServerSocket server ;
   private final int ServerPort = 8765;//要監控的port

   public SocketServer(){
      try{
         server = new ServerSocket(ServerPort);
      }catch(java.io.IOException e){
         System.out.println("Socket啟動有問題 !" );
         System.out.println("IOException :" + e.toString());
      }
   }

  public void run(){
    Socket socket ;
    java.io.BufferedInputStream in ;

    System.out.println("伺服器已啟動 !"  );
    while(!OutServer){
      socket = null;
      try{
        synchronized(server) {
           socket = server.accept();
        }
        System.out.println("取得連線 : InetAddress = " + socket.getInetAddress() );
        //TimeOut時間
        socket.setSoTimeout(15000);

        in = new java.io.BufferedInputStream(socket.getInputStream());
        byte[] b = new byte[1024];
        String data ="";
        int length;
        while((length = in.read(b))>0)//<=0的話就是結束了
        {
        data += new String(b, 0, length);
        }
     
         System.out.println("我取得的值:"+data);
         in.close();
         in = null ;
         socket.close();
      }catch(java.io.IOException e){
          System.out.println("Socket連線有問題 !" );
          System.out.println("IOException :" + e.toString());
      }
    }
  }

  public static void main(String args[]){
       (new SocketServer()).start();
  }
}

SocketClient

import java.net.InetSocketAddress;
import java.net.Socket;
import java.io.BufferedOutputStream;

public class SocketClient {
private String address = "127.0.0.1";// 連線的ip
private int port = 8765;// 連線的port

public SocketClient() {

Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
try {
client.connect(isa, 10000);
BufferedOutputStream out = new BufferedOutputStream(client
.getOutputStream());
// 送出字串
out.write("Send From Client ".getBytes());
out.flush();
out.close();
out = null;
client.close();
client = null;

} catch (java.io.IOException e) {
System.out.println("Socket連線有問題 !");
System.out.println("IOException :" + e.toString());
}
}

public static void main(String args[]) {
new SocketClient();
}
}

EWS API


  private ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

  public EWService(String email, String userPwd) throws Exception {
ExchangeCredentials credentials = new WebCredentials(email, userPwd);

service.setCredentials(credentials);
service.setUrl(new URI("https://XXX/ews/Exchange.asmx"));
}

  /*
* 寄信測試
*/
public void sendmailTest() throws Exception {
EmailMessage msg = new EmailMessage(service);
msg.setSubject("Hello world! 哈囉 ~ 世界");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS Managed API. 由 微軟提供 java api 測試發送"));
msg.getToRecipients().add("test@test.test");
msg.send();
}

完整 EWS API 說明和 sample at http://msdn.microsoft.com/en-us/library/exchange/dd633696(v=exchg.80)