Skip to content

Commit

Permalink
mongodb 示例 (#5)
Browse files Browse the repository at this point in the history
* mongodb示例

Co-authored-by: tianxiaodan <[email protected]>
  • Loading branch information
vangie and txd12 authored Mar 2, 2020
1 parent 322b6fe commit 19aaaa8
Show file tree
Hide file tree
Showing 22 changed files with 876 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,9 @@
* [Java 示例工程](rds-redis/java)
* [PHP 示例工程](rds-redis/php)
* [.NetCore 示例工程](rds-redis/dotnetcore)
* [MongoDB 数据库](rds-mongodb)
* [Nodejs 示例工程](rds-mongodb/nodejs)
* [Python 示例工程](rds-mongodb/python)
* [Java 示例工程](rds-mongodb/java)
* [PHP 示例工程](rds-mongodb/php)
* [.NetCore 示例工程](rds-mongodb/dotnetcore)
2 changes: 2 additions & 0 deletions rds-mongodb/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
php/extension/
php/vendor/
32 changes: 32 additions & 0 deletions rds-mongodb/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
STACK_NAME ?= mongo-test

start_mongo:
bin/start_mongo.sh

stop_mongo:
docker stop mongo_for_fc

clean:
docker rm -f mongo_for_fc

build:
IGNORE_TPL_VALIDATION=true fun build

deploy:
fun package
fun deploy --use-ros --stack-name $(STACK_NAME)

invoke_java:
IGNORE_TPL_VALIDATION=true fun invoke java

invoke_nodejs:
IGNORE_TPL_VALIDATION=true fun invoke nodejs

invoke_dotnetcore:
IGNORE_TPL_VALIDATION=true fun invoke dotnetcore

invoke_python:
IGNORE_TPL_VALIDATION=true fun invoke nodejs

invoke_php:
IGNORE_TPL_VALIDATION=true fun invoke php
74 changes: 74 additions & 0 deletions rds-mongodb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# 函数计算访问 MongoDB 示例集

## 依赖工具

本项目是在 MacOS 下开发的,涉及到的工具是平台无关的,对于 Linux 和 Windows 桌面系统应该也同样适用。在开始本例之前请确保如下工具已经正确的安装,更新到最新版本,并进行正确的配置。

* [Docker](https://www.docker.com/)
* [Funcraft](https://github.com/aliyun/fun)

Fun 工具依赖于 docker 来模拟本地环境。

对于 MacOS 用户可以使用 [homebrew](https://brew.sh/) 进行安装:

```bash
brew cask install docker
brew tap vangie/formula
brew install fun
```

Windows 和 Linux 用户安装请参考:

1. https://github.com/aliyun/fun/blob/master/docs/usage/installation.md

安装好后,记得先执行 `fun config` 初始化一下配置。

**注意**, 如果你已经安装过了 funcraft,确保 funcraft 的版本在 3.5.3 以上。

```bash
$ fun --version
3.5.3
```

## 初始化

```bash
git clone http://github.com/vangie/fc-db
cd fc-db/rds-mongodb
```

## 构建

```bash
make build
```

## 部署

```bash
make deploy
```

## 测试

```bash
# java
make invoke_java

# nodejs
make invoke_nodejs

# python
make invoke_python

# .NET
make invoke_dotnetcore
```

## 示例工程源码

* [Nodejs 示例工程](nodejs)
* [Python 示例工程](python)
* [Java 示例工程](java)
* [Dotnetcore 示例工程](dotnetcore)
* [PHP 示例工程](php)
15 changes: 15 additions & 0 deletions rds-mongodb/bin/start_mongo.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

CONTAINER_NAME=mongo_for_fc
USERNAME=mongoadmin
PASSWORD=secret

if [ ! "$(docker ps -a | grep $CONTAINER_NAME)" ]; then
docker run --name $CONTAINER_NAME \
-e MONGO_INITDB_ROOT_USERNAME=$USERNAME \
-e MONGO_INITDB_ROOT_PASSWORD=$PASSWORD \
-p 27017:27017 \
mongo
else
docker start $CONTAINER_NAME
fi
35 changes: 35 additions & 0 deletions rds-mongodb/dotnetcore/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.IO;
using System.Text;
using Aliyun.Serverless.Core;
using MongoDB.Bson;
using MongoDB.Driver;

namespace mongodb
{
public class MongoDBHandler
{
private static String dbName = Environment.GetEnvironmentVariable("MONGO_DATABASE");
private static String connectionUrl = Environment.GetEnvironmentVariable("MONGO_URL");
public Stream Handler(Stream input, IFcContext context)
{
var client = new MongoClient(connectionUrl);
var database = client.GetDatabase(dbName);
var collection = database.GetCollection<BsonDocument>("fc_col");
var document = new BsonDocument
{
{ "DEMO", "FC" },
{ "MSG", "Hello FunctionCompute For MongoDB" }
};
collection.InsertOne(document);
var doc = collection.Find(new BsonDocument{{ "DEMO", "FC"}}).FirstOrDefault();
Console.WriteLine(doc.ToString());

byte[] docBytes = Encoding.UTF8.GetBytes(doc.ToString());
MemoryStream output = new MemoryStream();
output.Write(docBytes, 0, docBytes.Length);
return output;
}

}
}
12 changes: 12 additions & 0 deletions rds-mongodb/dotnetcore/mongodb.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
<PackageReference Include="MongoDB.Driver" Version="2.10.2" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions rds-mongodb/java/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>fc-java-mongo</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>fc-java-mongo</name>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-core</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.1</version>
</dependency>
</dependencies>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.test.skip>true</maven.test.skip>
</properties>
</project>
54 changes: 54 additions & 0 deletions rds-mongodb/java/src/main/java/example/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package example;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class App implements StreamRequestHandler {

private static String dbName = System.getenv("MONGO_DATABASE");
private static String url = System.getenv("MONGO_URL");

@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

MongoClient mongoClient = new MongoClient(new MongoClientURI(url));

try {
MongoDatabase database = mongoClient.getDatabase(dbName);
MongoCollection<Document> collection = database.getCollection("fc_col");
Document doc = new Document();
String demoName = "FC";
doc.append("DEMO", "FC");
doc.append("MSG", "Hello FunctionCompute For MongoDB");
collection.insertOne(doc);
System.out.println("insert document: " + doc);

BsonDocument filter = new BsonDocument();
filter.append("DEMO", new BsonString(demoName));
MongoCursor<Document> cursor = collection.find(filter).iterator();

while (cursor.hasNext()) {
Document document = cursor.next();
System.out.println("find document: " + document);
outputStream.write(document.toString().getBytes());
}
} finally {
mongoClient.close();
}
}

}
39 changes: 39 additions & 0 deletions rds-mongodb/nodejs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

exports.handler = async (event, context, callback) => {

const dbName = process.env.MONGO_DATABASE;
const url = process.env.MONGO_URL;

const client = new MongoClient(url);

try {
await client.connect();
const db = client.db(dbName);

const demoName = "FC";
const doc = {
"DEMO": demoName,
"MSG": "Hello FunctionCompute For MongoDB"
};

let col = db.collection('fc_col');

let r = await col.insertOne(doc);
assert.equal(1, r.insertedCount);

const filter = { "DEMO": demoName };
let res = await col.findOne(filter);

console.log(res);
callback(null, res);

} catch (err) {
console.log(err.stack);
callback(err, "Error");
} finally {
client.close();
}
};
Loading

0 comments on commit 19aaaa8

Please sign in to comment.