问题描述
我无法在我的 redis 数据库中设置和检索带有重音符号的字符串.
带重音的字符已编码,我如何在设置时检索它们?
I do not manage to set and retrieve string with accents in my redis db.
Chars with accents are encoded, how can I retrieve them back as they where set ?
redis> set test téléphone
OK
redis> get test
"t\xc3\xa9l\xc3\xa9phone"
我知道这已经被问到了(http://stackoverflow.com/questions/6731450/redis-problem-with-accents-utf-8-encoding)但没有详细的答案.
I know this has already been asked(http://stackoverflow.com/questions/6731450/redis-problem-with-accents-utf-8-encoding) but there is no detailed answer.
推荐答案
Redis 服务器本身将所有数据存储为二进制对象,因此它不依赖于编码.服务器将只存储客户端发送的内容(包括 UTF-8 字符).
The Redis server itself stores all data as a binary objects, so it is not dependent on the encoding. The server will just store what is sent by the client (including UTF-8 chars).
以下是一些实验:
$ echo téléphone | hexdump -C
00000000 74 c3 a9 6c c3 a9 70 68 6f 6e 65 0a |t..l..phone.|
c3a9 是 'é' 字符的表示.
c3a9 is the representation of the 'é' char.
$ redis-cli
> set t téléphone
OK
> get t
"t\xc3\xa9l\xc3\xa9phone"
实际上数据是正确存储在Redis服务器中的.但是,当它在终端中启动时,Redis 客户端会解释输出并应用 sdscatrepr 函数 转换不可打印的字符(其定义取决于语言环境,并且可能因多字节字符而被破坏).
Actually the data is correctly stored in the Redis server. However, when it is launched in a terminal, the Redis client interprets the output and applies the sdscatrepr function to transform non printable chars (whose definition is locale dependent, and may be broken for multibyte chars anyway).
一个简单的解决方法是使用 'raw' 选项启动 redis-cli:
A simple workaround is to launch redis-cli with the 'raw' option:
$ redis-cli --raw
> get t
téléphone
您自己的应用程序可能会使用其中一个客户端库而不是 redis-cli,因此在实践中应该不成问题.
Your own application will probably use one of the client libraries rather than redis-cli, so it should not be a problem in practice.
这篇关于如何在redis中保存和检索带有重音符号的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!