溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么基于 Knative Serverless 技術實現(xiàn)天氣服務

發(fā)布時間:2021-12-16 16:35:42 來源:億速云 閱讀:103 作者:柒染 欄目:互聯(lián)網(wǎng)科技

本篇文章為大家展示了怎么基于 Knative Serverless 技術實現(xiàn)天氣服務,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

提到天氣預報服務,我們第一反應是很簡單的一個服務啊,目前網(wǎng)上有大把的天氣預報 API 可以直接使用,有必要去使用 Knative 搞一套嗎?殺雞用牛刀?先不要著急,我們先看一下實際的幾個場景需求:

  • 場景需求1:根據(jù)當?shù)貧v年的天氣信息,預測明年大致的高溫到來的時間

  • 場景需求2:近來天氣多變,如果明天下雨,能否在早上上班前,給我一個帶傘提醒通知

  • 場景需求3:領導發(fā)話:最近經(jīng)濟不景氣,公司財務緊張,那個服務器,你們提供天氣、路況等服務的那幾個小程序一起用吧,但要保證正常提供服務。

從上面的需求,我們其實發(fā)現(xiàn),要做好一個天氣預報的服務,也面臨內(nèi)憂(資源緊缺)外患(需求增加),并不是那么簡單的。不過現(xiàn)在更不要著急,我們可以使用 Knative 幫你解決上面的問題。

關鍵詞:天氣查詢、表格存儲,通道服務,事件通知

場景需求

首先我們來描述一下我們要做的天氣服務場景需求:

1. 提供對外的天氣預報 RESTful API

  • 根據(jù)城市、日期查詢(支持未來 3 天)國內(nèi)城市天氣信息

  • 不限制查詢次數(shù),支持較大并發(fā)查詢(1000)

2. 天氣訂閱提醒

  • 訂閱國內(nèi)城市天氣信息,根據(jù)實際訂閱城市區(qū)域,提醒明天下雨帶傘

  • 使用釘釘進行通知

整體架構

有了需求,那我們就開始如何基于 Knative 實現(xiàn)天氣服務。我們先看一下整體架構:

  • 通過 CronJob 事件源,每隔 3個 小時定時發(fā)送定時事件,將國內(nèi)城市未來3天的天氣信息,存儲更新到表格存儲

  • 提供 RESTful API 查詢天氣信息

  • 通過表格存儲提供的通道服務,實現(xiàn) TableStore 事件源

  • 通過 Borker/Trigger 事件驅動模型,訂閱目標城市天氣信息

  • 根據(jù)訂閱收到的天氣信息進行釘釘消息通知。如明天下雨,提示帶傘等

提供對外的天氣預報 RESTful API

對接高德開放平臺天氣預報 API

查詢天氣的 API 有很多,這里我們選擇高德開放平臺提供的天氣查詢 API,使用簡單、服務穩(wěn)定,并且該天氣預報 API 每天提供 100000 免費的調(diào)用量,支持國內(nèi) 3500 多個區(qū)域的天氣信息查詢。另外高德開放平臺,除了天氣預報,還可以提供 ip 定位、搜索服務、路徑規(guī)劃等,感興趣的也可以研究一下玩法。 登錄高德開放平臺: https://lbs.amap.com, 創(chuàng)建應用,獲取 Key 即可:

獲取Key之后,可以直接通過url訪問: https://restapi.amap.com/v3/weather/weatherInfo?city=110101&extensions=all&key=<用戶key>,返回天氣信息數(shù)據(jù)如下:

{
    "status":"1",
    "count":"1",
    "info":"OK",
    "infocode":"10000",
    "forecasts":[
        {
            "city":"杭州市",
            "adcode":"330100",
            "province":"浙江",
            "reporttime":"2019-09-24 20:49:27",
            "casts":[
                {
                    "date":"2019-09-24",
                    "week":"2",
                    "dayweather":"晴",
                    "nightweather":"多云",
                    "daytemp":"29",
                    "nighttemp":"17",
                    "daywind":"無風向",
                    "nightwind":"無風向",
                    "daypower":"≤3",
                    "nightpower":"≤3"
                },
                ...
            ]
        }
    ]
}

定時同步并更新天氣信息

同步并更新天氣信息

該功能主要實現(xiàn)對接高德開放平臺天氣預報 API, 獲取天氣預報信息,同時對接阿里云表格存儲服務(TableStore),用于天氣預報數(shù)據(jù)存儲。具體操作如下:

  • 接收 CloudEvent 定時事件

  • 查詢各個區(qū)域天氣信息

  • 將天氣信息存儲或者更新到表格存儲

在 Knative 中,我們可以直接創(chuàng)建服務如下:

apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
  name: weather-store
  namespace: default
spec:
  template:
    metadata:
      labels:
        app: weather-store
      annotations:
        autoscaling.knative.dev/maxScale: "20"
        autoscaling.knative.dev/target: "100"
    spec:
      containers:
        - image: registry.cn-hangzhou.aliyuncs.com/knative-sample/weather-store:1.2
          ports:
            - name: http1
              containerPort: 8080
          env:
          - name: OTS_TEST_ENDPOINT
            value: http://xxx.cn-hangzhou.ots.aliyuncs.com
          - name: TABLE_NAME
            value: weather
          - name: OTS_TEST_INSTANCENAME
            value: ${xxx} 
          - name: OTS_TEST_KEYID
            value: ${yyy}
          - name: OTS_TEST_SECRET
            value: ${Pxxx}
          - name: WEATHER_API_KEY
            value: xxx

關于服務具體實現(xiàn)參見 GitHub 源代碼: https://github.com/knative-sample/weather-store

創(chuàng)建定時事件

這里或許有疑問:為什么不在服務中直接進行定時輪詢,非要通過 Knative Eventing 搞一個定時事件觸發(fā)執(zhí)行調(diào)用?那我們要說明一下,Serverless 時代下就該這樣玩-按需使用。千萬不要在服務中按照傳統(tǒng)的方式空跑這些定時任務,親,這是在持續(xù)浪費計算資源。 言歸正傳,下面我們使用 Knative Eventing 自帶的定時任務數(shù)據(jù)源(CronJobSource),觸發(fā)定時同步事件。 創(chuàng)建 CronJobSource 資源,實現(xiàn)每 3 個小時定時觸發(fā)同步天氣服務(weather-store),WeatherCronJob.yaml 如下:

apiVersion: sources.eventing.knative.dev/v1alpha1
kind: CronJobSource
metadata:
  name: weather-cronjob
spec:
  schedule: "0 */3 * * *"
  data: '{"message": "sync"}'
  sink:
    apiVersion: serving.knative.dev/v1alpha1
    kind: Service
    name: weather-store

執(zhí)行命令:

kubectl apply -f WeatherCronJob.yaml

現(xiàn)在我們登錄阿里云表格存儲服務,可以看到天氣預報數(shù)據(jù)已經(jīng)按照城市、日期的格式同步進來了。

提供天氣預報查詢 RESTful API

有了這些天氣數(shù)據(jù),可以隨心所欲的提供屬于我們自己的天氣預報服務了(感覺像是承包了一塊地,我們來當?shù)刂鳎@里沒什么難點,從表格存儲中查詢對應的天氣數(shù)據(jù),按照返回的數(shù)據(jù)格式進行封裝即可。 在 Knative 中,我們可以部署 RESTful API 服務如下:

apiVersion: serving.knative.dev/v1alpha1
kind: Service
metadata:
  name: weather-service
  namespace: default
spec:
  template:
    metadata:
      labels:
        app: weather-service
      annotations:
        autoscaling.knative.dev/maxScale: "20"
        autoscaling.knative.dev/target: "100"
    spec:
      containers:
        - image: registry.cn-hangzhou.aliyuncs.com/knative-sample/weather-service:1.1
          ports:
            - name: http1
              containerPort: 8080
          env:
          - name: OTS_TEST_ENDPOINT
            value: http://xxx.cn-hangzhou.ots.aliyuncs.com
          - name: TABLE_NAME
            value: weather
          - name: OTS_TEST_INSTANCENAME
            value: ${xxx} 
          - name: OTS_TEST_KEYID
            value: ${yyy}
          - name: OTS_TEST_SECRET
            value: ${Pxxx}

具體實現(xiàn)源代碼 GitHub 地址: https://github.com/knative-sample/weather-service查詢天氣 RESTful API:

  • 請求URL GET /api/weather/query

參數(shù):
cityCode:城市區(qū)域代碼。如北京市區(qū)域代碼:110000
date:查詢?nèi)掌?。如格式?019-09-26
  • 返回結果

{
    "code":200,
    "message":"",
    "data":{
        "adcode":"110000",
        "city":"北京市",
        "date":"2019-09-26",
        "daypower":"≤3",
        "daytemp":"30",
        "dayweather":"晴",
        "daywind":"東南",
        "nightpower":"≤3",
        "nighttemp":"15",
        "nightweather":"晴",
        "nightwind":"東南",
        "province":"北京",
        "reporttime":"2019-09-25 14:50:46",
        "week":"4"
    }
}

查詢:杭州,2019-09-26天氣預報信息示例 測試地址: http://weather-service.default.knative.kuberun.com/api/weather/query?cityCode=330100&date=2019-11-06另外城市區(qū)域代碼表可以在上面提供的源代碼 GitHub 中可以查看,也可以到高德開放平臺中下載: https://lbs.amap.com/api/webservice/download

天氣訂閱提醒

首先我們介紹一下表格存儲提供的通道服務。通道服務(Tunnel Service)是基于表格存儲數(shù)據(jù)接口之上的全增量一體化服務。通道服務為您提供了增量、全量、增量加全量三種類型的分布式數(shù)據(jù)實時消費通道。通過為數(shù)據(jù)表建立數(shù)據(jù)通道,您可以簡單地實現(xiàn)對表中歷史存量和新增數(shù)據(jù)的消費處理。通過數(shù)據(jù)通道可以進行數(shù)據(jù)同步、事件驅動、流式數(shù)據(jù)處理以及數(shù)據(jù)搬遷。這里事件驅動正好契合我們的場景。

自定義 TableStore 事件源

在 Knative 中自定義事件源其實很容易,可以參考官方提供的自定義事件源的實例: https://github.com/knative/docs/tree/master/docs/eventing/samples/writing-a-source。 我們這里定義數(shù)據(jù)源為 AliTablestoreSource。代碼實現(xiàn)主要分為兩部分:

  1. 資源控制器-Controller:接收 AliTablestoreSource 資源,在通道服務中創(chuàng)建 Tunnel。

  2. 事件接收器-Receiver:通過 Tunnel Client 監(jiān)聽事件,并將接收到的事件發(fā)送到目標服務( Broker)

關于自定義 TableStore 事件源實現(xiàn)參見 GitHub 源代碼: https://github.com/knative-sample/tablestore-source

部署自定義事件源服務如下: 從 https://github.com/knative-sample/tablestore-source/tree/master/config 中可以獲取事件源部署文件,執(zhí)行下面的操作

kubectl apply -f 200-serviceaccount.yaml -f 201-clusterrole.yaml -f 202-clusterrolebinding.yaml -f 300-alitablestoresource.yaml -f 400-controller-service.yaml -f 500-controller.yaml -f 600-istioegress.yaml

部署完成之后,我們可以看資源控制器已經(jīng)開始運行:

[root@iZ8vb5wa3qv1gwrgb3lxqpZ config]# kubectl -n knative-sources get pods
NAME                                 READY   STATUS    RESTARTS   AGE
alitablestore-controller-manager-0   1/1     Running   0          4h22m

創(chuàng)建事件源

由于我們是通過 Knative Eventing 中 Broker/Trigger 事件驅動模型對天氣事件進行處理。首先我們創(chuàng)建用于數(shù)據(jù)接收的 Broker 服務。

創(chuàng)建 Broker

apiVersion: eventing.knative.dev/v1alpha1
kind: Broker
metadata:
  name: weather
spec:
  channelTemplateSpec:
    apiVersion: messaging.knative.dev/v1alpha1
    kind: InMemoryChannel

創(chuàng)建事件源實例

這里需要說明一下,創(chuàng)建事件源實例其實就是在表格存儲中創(chuàng)建通道服務,那么就需要配置訪問通道服務的地址、accessKeyId和accessKeySecret,這里參照格式:{ "url":"https://xxx.cn-beijing.ots.aliyuncs.com/", "accessKeyId":"xxxx","accessKeySecret":"xxxx" } 設置并進行base64編碼。將結果設置到如下 Secret 配置文件alitablestore 屬性中:

apiVersion: v1
kind: Secret
metadata:
  name: alitablestore-secret
type: Opaque
data:
  # { "url":"https://xxx.cn-beijing.ots.aliyuncs.com/", "accessKeyId":"xxxx","accessKeySecret":"xxxx" }
  alitablestore: "<base64>"

創(chuàng)建 RBAC 權限

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: eventing-sources-alitablestore
subjects:
- kind: ServiceAccount
  name: alitablestore-sa
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: eventing-sources-alitablestore-controller
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: alitablestore-sa
secrets:
- name: alitablestore-secret

創(chuàng)建 AliTablestoreSource 實例,這里我們設置接收事件的 sink 為上面創(chuàng)建的 Broker 服務。

---
apiVersion: sources.eventing.knative.dev/v1alpha1
kind: AliTablestoreSource
metadata:
  labels:
    controller-tools.k8s.io: "1.0"
  name: alitablestoresource
spec:
  # Add fields here
  serviceAccountName: alitablestore-sa
  accessToken:
    secretKeyRef:
      name: alitablestore-secret
      key: alitablestore
  tableName: weather
  instance: knative-weather
  sink:
    apiVersion: eventing.knative.dev/v1alpha1
    kind: Broker
    name: weather

創(chuàng)建完成之后,我們可以看到運行中的事件源:

[root@iZ8vb5wa3qv1gwrgb3lxqpZ config]# kubectl get pods
NAME                                                              READY   STATUS      RESTARTS   AGE
tablestore-alitablestoresource-9sjqx-656c5bf84b-pbhvw             1/1     Running     0          4h9m

訂閱事件和通知提醒

創(chuàng)建天氣提醒服務

如何進行釘釘通知呢,我們可以創(chuàng)建一個釘釘?shù)娜航M(可以把家里人組成一個釘釘群,天氣異常時,給家人一個提醒),添加群機器人:

獲取 webhook :

這里我們假設北京(110000),日期:2019-10-13, 如果天氣有雨,就通過釘釘發(fā)送通知提醒,則服務配置如下:

apiVersion: serving.knative.dev/v1beta1
kind: Service
metadata:
  name: day-weather
spec:
  template:
    spec:
      containers:
      - args:
        - --dingtalkurl=https://oapi.dingtalk.com/robot/send?access_token=xxxxxx
        - --adcode=110000
        - --date=2019-10-13
        - --dayweather=雨
        image: registry.cn-hangzhou.aliyuncs.com/knative-sample/dingtalk-weather-service:1.2

關于釘釘提醒服務具體實現(xiàn)參見 GitHub 源代碼: https://github.com/knative-sample/dingtalk-weather-service

創(chuàng)建訂閱

最后我們創(chuàng)建 Trigger訂閱天氣事件,并且觸發(fā)天氣提醒服務:

apiVersion: eventing.knative.dev/v1alpha1
kind: Trigger
metadata:
  name: weather-trigger
spec:
  broker: weather
  subscriber:
    ref:
      apiVersion: serving.knative.dev/v1alpha1
      kind: Service
      name: day-weather

訂閱之后,如果北京(110000),日期:2019-10-13, 天氣有雨,會收到如下的釘釘提醒:

這里其實還有待完善的地方:

  • 是否可以基于城市進行訂閱(只訂閱目標城市)?

  • 是否可以指定時間發(fā)送消息提醒(當天晚上 8 點準時推送第 2 天的天氣提醒信息)?

上述內(nèi)容就是怎么基于 Knative Serverless 技術實現(xiàn)天氣服務,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI