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");
    

      显示

  • 相关阅读:
    变形金刚2中的各个角色,及车型(带图)第二篇。
    文字效果。这个比较好!
    发一个非常简单的效果,是在浏览器里面上下左右都居中的问题
    等高的css效果,很少见,原来都是用js 的,这回也有css的了,哈哈
    ie6最小宽度问题
    变形金刚2中的各个角色,及车型(带图)第一篇。
    差点吓死我,擦
    单车Eason
    学习了下简单的光照模型
    自我介绍
  • 原文地址:https://www.cnblogs.com/Jomini/p/13040765.html
Copyright © 2011-2022 走看看