use*_*328 5 rpc json-rpc data-serialization avro avro4s
我是AVRO的新手,请问这是一个简单的问题。我有一个用例,其中我使用AVRO模式进行记录调用。
假设我有Avro模式
{
"name": "abc",
"namepsace": "xyz",
"type": "record",
"fields": [
{"name": "CustId", "type":"string"},
{"name": "SessionId", "type":"string"},
]
}
Run Code Online (Sandbox Code Playgroud)
现在,如果输入像
{
"CustId" : "abc1234"
"sessionID" : "000-0000-00000"
}
Run Code Online (Sandbox Code Playgroud)
我想对这些字段使用一些正则表达式验证,并且仅当输入格式如上所示时才接受此输入。有什么方法可以在avro模式中指定包含正则表达式的表达式吗?
还有其他支持这样的数据序列化格式吗?
您应该能够为此使用自定义逻辑类型。然后,您将直接在架构中包含正则表达式。
例如,以下是在 JavaScript 中实现的方法:
var avro = require('avsc'),
util = require('util');
/**
* Sample logical type that validates strings using a regular expression.
*
*/
function ValidatedString(attrs, opts) {
avro.types.LogicalType.call(this, attrs, opts);
this._pattern = new RegExp(attrs.pattern);
}
util.inherits(ValidatedString, avro.types.LogicalType);
ValidatedString.prototype._fromValue = function (val) {
if (!this._pattern.test(val)) {
throw new Error('invalid string: ' + val);
}
return val;
};
ValidatedString.prototype._toValue = ValidatedString.prototype._fromValue;
Run Code Online (Sandbox Code Playgroud)
以及您将如何使用它:
var type = avro.parse({
name: 'Example',
type: 'record',
fields: [
{
name: 'custId',
type: 'string' // Normal (free-form) string.
},
{
name: 'sessionId',
type: {
type: 'string',
logicalType: 'validated-string',
pattern: '^\\d{3}-\\d{4}-\\d{5}$' // Validation pattern.
}
},
]
}, {logicalTypes: {'validated-string': ValidatedString}});
type.isValid({custId: 'abc', sessionId: '123-1234-12345'}); // true
type.isValid({custId: 'abc', sessionId: 'foobar'}); // false
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关实现和使用逻辑类型的更多信息。
编辑:对于 Java 实现,我相信您会想要查看以下类:
LogicalType,您需要扩展的基础。Conversion, 执行数据的转换(或在您的情况下进行验证)。LogicalTypes以及Conversions,现有实现的一些示例。TestGenericLogicalTypes,可以提供有用的起点的相关测试。