简体   繁体   English

Redis:我应该将IP转换为整数吗?

[英]Redis: should I convert IPs into integers?

I need to store IP addresses in a redis hash. 我需要将IP地址存储在Redis哈希中。

Will there be considerable memory savings if the IP is stored as an integer instead of a string? 如果IP以整数而不是字符串存储,会节省大量内存吗?

I would be using Ruby's IPAddr to convert the IP to an int. 我将使用Ruby的IPAddr将IP转换为int。

It depends on how you do it. 这取决于您的操作方式。 In Redis keys and (leaf) values are strings. 在Redis中,键和(叶)值是字符串。 If you would convert an IP address to an int and send it to Redis like the following code you wouldn't save much: 如果将IP地址转换为int并将其发送给Redis,如以下代码所示,将不会节省很多:

redis.hset("xyz", "ip", IPAddr.new(ip).to_i)

The IP "255.255.255.255", for example, is 15 bytes in dotted quad form, its integer representation "4294967295" is ten bytes when saved as a string, which is what the code above will do. 例如,IP“ 255.255.255.255”为点分四边形形式的15个字节,当保存为字符串时,其整数表示“ 4294967295”为10个字节,这就是上面的代码所要做的。

To get down to just four bytes stored in Redis you would have to send the raw bytes "\\xFF\\xFF\\xFF\\xFF". 要减少到Redis中存储的四个字节,您必须发送原始字节“ \\ xFF \\ xFF \\ xFF \\ xFF”。

In Ruby you would do it this way: 在Ruby中,您可以这样做:

packed_ip = IPAddr.new(ip).hton
redis.hset("xyz", "ip", packed_ip)

And then when you read it back 然后当你读回它

packed_ip = redis.hget("xyz", "ip")
ip = IPAddr.ntop(packed_ip)

What IPAddr.hton and IPAddr.ntop do is this: IPAddr.htonIPAddr.ntop作用是这样的:

packed_ip = ip.split('.').map(&:to_i).pack('C4') # hton
ip = packed_ip.unpack('C4').join('.') # ntop

Then there's the whole thing about IPv6 and whatnot, but I think IPAddr has you covered there. 然后是有关IPv6的全部内容,但我想IPAddr已经为您介绍了。

You may wish to reconsider your approach a little as well, with the advent of IPv6 storing as an integer would be a very bad idea if you ever wish to convert your application to use IPv6 (or even just support it). 您可能还希望重新考虑一下您的方法,如果您希望将应用程序转换为使用IPv6(甚至只是支持它),那么将IPv6存储为整数将是一个非常糟糕的主意。

These days memory/disk space is cheap so you'd be better investing in a workable future proof solution than worry about disk space if you can. 如今,内存/磁盘空间很便宜,因此,如果可以的话,与担心磁盘空间相比,最好投资于可行的面向未来的解决方案。

In this case a string would still be the best option since you can then utilize IPv6 and IPv4 in the same field. 在这种情况下,字符串仍然是最佳选择,因为您可以在同一字段中使用IPv6和IPv4。

If you store and ip as an integer it will use up 4 bytes. 如果您将ip存储为一个整数,它将占用4个字节。 as a string "abc.def.ghi.jkl" it will use up 16 bytes when stored as a null-terminated ascii string, so it is at least a factor of 4 or even 7+ if stored as an unicode string. 作为字符串“ abc.def.ghi.jkl”存储为空终止的ascii字符串时,它将用完16个字节,因此,如果存储为unicode字符串,则至少是4甚至7+的因数。 Also searching for integers is much faster than for strings because your processor is optimized to compare integers... 而且搜索整数要比字符串搜索快得多,因为您的处理器已经过优化以比较整数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM