2023年8月15日星期二

我的随机数3——Google云Cloud Function

 几年前一次开会无聊,就研究Google云的Cloud Function,基于java语言的Hello World例程,写了一个能够返回[0,99.99]随机数的函数。其中随机数用的是java的Random类,没有用比较复杂的SecureRandom类。代码如下:

package com.example.functions;

import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Random;

public class HelloWorld implements HttpFunction {
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
Random r = new Random();
int i = r.nextInt(10000);
String str = String.format("%.2f", i / 100.0);
BufferedWriter writer = response.getWriter();
writer.write(str);
}
}

美中不足的是,Google云的Cloud Function在中国大陆不能直接访问,每次都要跳转一下。此外URL比较长,所以我用CloudFlare的redirect功能又重定向了一下。入口如下,欢迎大家使用。

https://www.ming.gq/r

没有评论:

发表评论