• 使用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");
    

      显示

  • 相关阅读:
    Understanding identities in IIS
    Name your feature branches by convention
    Branch policies on Azure Repos
    Use Git Credential Managers to Authenticate to Azure Repos
    How do I force my .NET application to run as administrator?
    UML的类型
    ASP.NET Error Handling
    通过泛型,将string转换为指定类型
    Spring Session + Redis实现分布式Session共享
    MongoDB中的数据导出为excel CSV 文件
  • 原文地址:https://www.cnblogs.com/Jomini/p/13040765.html
Copyright © 2020-2023  润新知