新闻中心
新闻中心与新手教程
新闻中心与新手教程
发布时间:2024-10-13 01:13:09
让我们深入探讨这个serverless job的每个部分,以及如何进行更全面的实现和优化。
// serverless.yml
service: hot-news-fetcher
provider:
name: aws
runtime: nodejs14.x
stage: ${opt:stage, 'dev'}
region: ${opt:region, 'us-east-1'}
environment:
dynamodb_table: ${self:service}-${self:provider.stage}
iamrolestatements:
- effect: allow
action:
- dynamodb:putitem
resource: "arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.dynamodb_table}"
functions:
fetchhotnews:
handler: handler.fetchhotnews
events:
- schedule: rate(1 hour)
timeout: 30 # 设置超时时间为30秒
memorysize: 256 # 设置内存大小为256mb
resources:
resources:
hotnewstable:
type: aws::dynamodb::table
properties:
tablename: ${self:provider.environment.dynamodb_table}
attributedefinitions:
- attributename: id
attributetype: s
keyschema:
- attributename: id
keytype: hash
billingmode: pay_per_request
// handler.js
const axios = require('axios');
const aws = require('aws-sdk');
const dynamodb = new aws.dynamodb.documentclient();
module.exports.fetchhotnews = async (event) => {
console.log('fetching hot news started');
try {
// 1. 从新闻api获取热搜数据
const response = await axios.get('https://api.example.com/hot-news', {
timeout: 5000 // 设置5秒超时
});
const hotnews = response.data;
console.log(`fetched ${hotnews.length} hot news items`);
// 2. 处理并存储数据
const batchsize = 25; // dynamodb 批量写入上限
for (let i = 0; i < hotnews.length; i += batchsize) {
const batch = hotnews.slice(i, i + batchsize);
const putrequests = batch.map(news => ({
putrequest: {
item: {
id: news.id,
title: news.title,
url: news.url,
timestamp: new date().toisostring(),
category: news.category || 'uncategorized',
source: news.source || 'unknown'
}
}
}));
await dynamodb.batchwrite({
requestitems: {
[process.env.dynamodb_table]: putrequests
}
}).promise();
console.log(`stored batch ${i / batchsize + 1}`);
}
return {
statuscode: 200,
body: json.stringify({ message: `successfully fetched and stored ${hotnews.length} hot news items` })
};
} catch (error) {
console.error('error fetching hot news:', error);
// 细分错误类型
if (error.response) {
// api 响应错误
console.error(`api responded with status ${error.response.status}`);
} else if (error.request) {
// 请求未收到响应
console.error('no response received from api');
} else {
// 其他错误
console.error('error setting up request:', error.message);
}
return {
statuscode: 500,
body: json.stringify({ message: 'error fetching hot news', error: error.message })
};
}
};
现在让我们详细解释这个增强版的serverless job:
environment:
dynamodb_table: ${self:service}-${self:provider.stage}
iamrolestatements:
- effect: allow
action:
- dynamodb:putitem
resource: "arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.dynamodb_table}"
timeout: 30
memorysize: 256
resources:
resources:
hotnewstable:
type: aws::dynamodb::table
properties:
tablename: ${self:provider.environment.dynamodb_table}
attributedefinitions:
- attributename: id
attributetype: s
keyschema:
- attributename: id
keytype: hash
billingmode: pay_per_request
const batchsize = 25;
for (let i = 0; i < hotnews.length; i += batchsize) {
const batch = hotnews.slice(i, i + batchsize);
// ... 批量写入逻辑
}
item: {
// ... 其他字段
category: news.category || 'uncategorized',
source: news.source || 'unknown'
}
const response = await axios.get('https://api.example.com/hot-news', {
timeout: 5000 // 设置5秒超时
});
要有效地排查故障,您可以:
这个增强版的serverless job提供了更多的错误处理、性能优化和可靠性保证。它应该能够更好地处理各种边缘情况,并提供更丰富的日志信息用于故障排查。
感谢提供:05互联