0 环境
- 系统环境: centos7
- 编辑器: xshell
- IDE:IDEA
1 前言
2 准备
redis这块需要设置一下redis.conf 关闭保护模式和注释掉密码那行 redis-server xxx.conf 开启它 比如我用windows 可以cmd 在dos界面 telnet host port (telnet 192,168.1.123 6379) 测试跳到一个黑窗口 说明OK了 直接上代码即可
3 代码
public class SocketRedisClient {
private Socket socket;
// 初始化
public SocketRedisClient() {
try {
this.socket = new Socket(host, 6382);
} catch (IOException e) {
e.printStackTrace();
System.out.println("连接失败!!!");
}
}
/**
* 参考 * 参数数量
$ 参数字节数
参数数据
* SET mykey "Hello"
* *3 --> 整的参数数量 $3 --> set字符串的长度 后面类似
* *3
$3
SET
$7
myredis
$3
why
* @param key
* @param value
* @return
*/
public String set(String key, String value) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("*3")
.append("
")
.append("$")
.append("SET".length())
.append("
")
.append("SET")
.append("
")
.append("$")
.append(key.getBytes().length)
.append("
")
.append(key)
.append("
")
.append("$")
.append(value.getBytes().length)
.append("
")
.append(value)
.append("
");
// 打印出来
System.out.println(builder.toString());
socket.getOutputStream().write(builder.toString().getBytes());
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
return new String(bytes);
}
/**
* 获取key
* @param key
* @return
*/
public String get(String key) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("*2")
.append("
")
.append("$")
.append("GET".length())
.append("
")
.append("GET")
.append("
")
.append("$")
.append(key.getBytes().length)
.append("
")
.append(key)
.append("
");
// 打印出来
System.out.println(builder.toString());
socket.getOutputStream().write(builder.toString().getBytes());
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
return new String(bytes);
}
public static void main(String[] args) throws IOException {
String set = new SocketRedisClient().set("myredis", "why");
System.out.println(set);
System.out.println("-------------------------------------");
String get = new SocketRedisClient().get("myredis");
System.out.println(get);
}
}
3 结果
*3
$3
SET
$7
myredis
$3
why
+OK
-------------------------------------
*2
$3
GET
$7
myredis
$3
why