//存储表的每一行
127.0.0.1:6379> hmset {ip}:1 city P1 min 0 max 100
OK
127.0.0.1:6379> hmset {ip}:2 city P2 min 101 max 200
OK
127.0.0.1:6379> hmset {ip}:3 city P3 min 201 max 300
OK
127.0.0.1:6379> hmset {ip}:4 city P4 min 301 max 400
OK
public static void main(String[] args) throws IOException {
File file = new File("E:/doc/ipcountry_tab_orderby_end_asc.txt");
File hmsetFile = new File("E:/doc/ip_country_redis_cmd.txt");
File zaddFile = new File("E:/doc/ip_country_redis_zadd.txt");
List<String> lines = FileUtils.readLines(file);
int i = 0;
StringBuilder rows = new StringBuilder();
StringBuilder ends = new StringBuilder();
for (String str : lines) {
if (StringUtils.isEmpty(str)) {
continue;
}
//skip first line
if (i == 0) {
i++;
continue;
}
i++;
//"IPSTART""IPSTARTDIGITAL""IPEND""IPENDDIGITAL""COUNTRY""CITY""TYPE""REGISTRY""ADRESS""PROVINCE"
//0 1 2 3 4 5 6 7 8 9
String[] parts = str.split("\t");
String start = parts[1];
String end = parts[3];
String country = parts[4];
String city = parts[5];
String type = parts[6];
String registry = parts[7];
String address = parts[8];
String province = parts[9];
//String cmd = "hmset {ip}:" + (i++) + " start " + start + " end " + end + " country " + country + " city " + city + " type " + type + " registry " + registry + " address " + address + " province " + province;
*3
$3
set
$2
ab
$4
1234
注意每一行都是以<cr><lf>(也就是\r\n)结尾
3.查询
使用spring redis
关键代码:
long min = ip;//转换成数字的IP
long max = Long.MAX_VALUE;
long offset = 0;
long count = 1;
Set<String> result = redisTemplate.opsForZSet().rangeByScore(zSetName, min, max, offset, count);
final String ipKey = redisIprowPrefix + score;
String city = redisTemplate.execute(new RedisCallback<String>(){
@Override
public String doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] key = redisTemplate.getStringSerializer().serialize(
ipKey);
if (connection.exists(key)) {
List<byte[]> value = connection.hMGet(
key,
redisTemplate.getStringSerializer().serialize(
"city")
);
String city = redisTemplate.getStringSerializer()
.deserialize(value.get(0));
return city;
}
return null;
}