zoukankan      html  css  js  c++  java
  • 使用Socket访问redis客户端

    使用Socket访问redis客户端

    import java.io.IOException;
    import java.net.Socket;
    
    public class RedisDemoClient {
        
        Socket redisConnection = null;
        
        public RedisDemoClient(String host, int port) throws IOException{
            redisConnection = new Socket(host, port);
        }
        
        public void set(String key, String value) throws IOException{
            
            StringBuilder request = new StringBuilder();
            
            request.append("*3").append("
    ");
            
            request.append("$3").append("
    "); //参数的长度
            request.append("SET").append("
    "); // 参数的值
            
            request.append("$").append(key.getBytes().length).append("
    ");
            request.append(key).append("
    ");
            
            request.append("$").append(value.getBytes().length).append("
    ");
            request.append(value).append("
    ");
            
            System.out.println("这就是客户端发给redis服务器数据:");
            System.out.println(request);
            
            // 发送数据到redis服务器
            redisConnection.getOutputStream().write(request.toString().getBytes());
            
            //如何接受redis服务器的相应
            byte[] response = new byte[1024];
            redisConnection.getInputStream().read();    
        }
        
        public static void main(String[] args) throws IOException{
            RedisDemoClient redisDemoClient = new RedisDemoClient("127.0.0.1",6379);
            redisDemoClient.set("testKey", "testValue");
        }
        
    
    }

    使用console可以看到

    get

    	public String get(String key) throws IOException {
    
    		StringBuilder request = new StringBuilder();
    		request.append("*2").append("
    ");
    
    		request.append("GET").append("
    ");
    
    		request.append("$").append(key.getBytes().length).append("
    ");
    		request.append(key).append("
    ");
    
    		System.out.println("这就是客户端发送给Redis服务器的数据");
    		System.out.println(request);
    
    		redisConnection.getOutputStream().write(request.toString().getBytes());
    
    		// 如何接受redis 服务器的响应
    		byte[] response = new byte[1024];
    		redisConnection.getInputStream().read(response);
    
    		return new String(response);
    
    	}
    

      测试

    redisDemoClient.get("testKey");
    

      显示

  • 相关阅读:
    Vue 函数
    VUE 基础语法
    C# txt文件操作
    C# 添加应用程序包
    Js 倒计时跳转
    Redis集群(主从集群)(一)
    JAVA基础总结001(《JAVA核心技术》)
    Linux学习001——文件和用户
    Linux——ELK集群搭建
    Linux安装jdk
  • 原文地址:https://www.cnblogs.com/Jomini/p/13040765.html
Copyright © 2011-2022 走看看