社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
昨天遇到了一个奇葩的需求:把伪造的数据持久化到Linux服务器的Redis中
要说的话,其实也是很简单的。大概有那么几种方法可以实例化到Redis中。
- 直接在Linux上使用Redis 命令把相应的key值和value值写入。
- 写一个.java的方法,使用jedis 把相应的key 和value写入到Redis中
但是,由于数据条数很多,且都是比较长的JSON字符串。所以我不大可能会直接在Linux上操作Redis客户端。所以简便有效的方式就是写一个.java 文件批量处理然后写入。
那么问题来了:
我的.java文件需要在Linux上使用javac编译并运行。
但是由于我的java文件中import有第三方jar的内容,直接进行javac编译的话会报错。
代码如下:
package com.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class AddCompleteInfo {
static ShardedJedisPool pool;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(100);
config.setMaxIdle(20); // 对象最大空闲时间
config.setMaxWaitMillis(5000); // 获取对象最大等待时间。
config.setTestOnBorrow(true);
String host = "127.0.0.1";
int port = 6379;
List<JedisShardInfo> jdsInfoList = new ArrayList<JedisShardInfo>(2);
JedisShardInfo infoA = new JedisShardInfo(host, port);
jdsInfoList.add(infoA);
pool = new ShardedJedisPool(config, jdsInfoList);
}
public static void main(String[] args) {
String file = "/testJva/infroad.txt";
String reader = AddCompleteInfo.reader(file);
Pattern p = Pattern.compile("&");
String[] split = p.split(reader);
for (String string : split) {
System.out.println("分开的值是:"+string);
JSONObject parseObject = JSON.parseObject(string);
String token = parseObject.getString("token");
System.out.println("token的值是:"+token);
ShardedJedis jedis = pool.getResource();
jedis.set(token, string);
jedis.sadd("ALLTOKEN", token);
jedis.sadd("COMPLETED", token);
if (jedis != null)
jedis.close();
}
public static String reader(String filePath) {
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = bufferedReader.readLine();
while (lineTxt != null) {
return lineTxt;
}
}
} catch (UnsupportedEncodingException | FileNotFoundException e) {
System.out.println("Cannot find the file specified!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error reading file content!");
e.printStackTrace();
}
return null;
}
}
最后使用Eclipse将只包含主要代码的java项目,打成一个Runnable JAR file的 jar包
然后在Linux上使用,java -jar + jar包名称 的方式来运行,这样,就可以直接使得.java文件中的main方法运行下去
具体的过程看下图:
在晚上上述三步之后,就完成了编译的过程。接着需要把输出的jar包上传到服务器上进行运行。
infroad.txt 这个里面是包含了我json字符串的文件,里面每一段json都是按照&作为分割符号进行分割的。具体看代码
然后使用命令行运行这个jar文件即可。
java -jar kkkkkkkskk.jar
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!