这里我们就在虚拟机中安装redis,并且使用java和python实现简单的操作。深情是我承担不起的重担,情话只是偶尔兑现的谎言。

redis的使用

下载地址:https://redis.io/。安装过程,可以参考博客:http://www.linuxidc.com/Linux/2014-05/101544.htm

启动服务,参考博客:http://www.linuxidc.com/Linux/2014-05/101544p2.htm

一、非本地访问redis服务器,需要修改redis.conf文件的内容

redis.conf文件的位置:tar解压的位置/redis.3.2.8里面。

  • 注释bind 127.0.0.1,使所有的主机都可以访问
  • 修改protected-mode的yes为no

如果要生效还需要先停掉redis的服务,再redis-server redis.conf。这个redis.conf需要带上。

参考博客: http://blog.csdn.net/only1994/article/details/52785306

二、java的测试使用

依赖jar包:jedis-2.9.0.jar和commons-pool2-2.4.2.jar。使用maven,需要在pom.xml文件中添加内容:

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

具体的java代码如下:

public void redis_1() {
Jedis jedis = new Jedis("192.168.146.131", 6379); // 测试用的是虚拟机
jedis.set("foo", "bar");
String value = jedis.get("foo");
jedis.close();
System.out.println(value); // foo
}

三、对于Jedis原理的理解

我们通过socket连接redis服务器,发送请求命令的数据,然后打印返回的数据。

package com.linux.huhx.redis;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket; /**
* @Author: huhx
* @Date: 2017-11-23 下午 5:48
*/
public class RedisTest {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 6379);
socket.setReuseAddress(true);
String data = "get username\n";
socket.getOutputStream().write(data.getBytes()); InputStream inputStream = socket.getInputStream();
int length = inputStream.available();
byte[] buffer = new byte[length];
inputStream.read(buffer); // 对buffer做处理
String string = new String(buffer, "utf-8");
System.out.println(string);
socket.close();
}
}

如下是打印的结果,可以得到redis中username对应的value。

$4
huhx

  其实上述JRedis的原理和这个差不多,都是通过socket连接,发送命令数据到服务器。然后得到响应的数据,现在我们就JRedis的源码对这个流程做一个分析。首先是Jedis jedis = new Jedis("127.0.0.1", 6379);初始化Connection的地址和端口。

public Connection(final String host, final int port) {
this.host = host;
this.port = port;
}

String value = jedis.get("username");这段代码的源码如下:

public String get(final String key) {
checkIsInMultiOrPipeline();
client.sendCommand(Protocol.Command.GET, key);
return client.getBulkReply();
}

checkIsInMultiOrPipeline方法是检查Multi和Pipeline,具体的这两个是开什么的,目前不怎么了解。后续补上

protected void checkIsInMultiOrPipeline() {
if (client.isInMulti()) {
throw new JedisDataException(
"Cannot use Jedis when in Multi. Please use Transation or reset jedis state.");
} else if (pipeline != null && pipeline.hasPipelinedResponse()) {
throw new JedisDataException(
"Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state .");
}
}

我们的重点代码是client.sendCommand(Protocol.Command.GET, key);如下:

protected Connection sendCommand(final Command cmd, final String... args) {
// 对请求的参数utf-8编码
final byte[][] bargs = new byte[args.length][];
for (int i = 0; i < args.length; i++) {
bargs[i] = SafeEncoder.encode(args[i]);
}
return sendCommand(cmd, bargs);
}

sendCommand的方法如下:

protected Connection sendCommand(final Command cmd, final byte[]... args) {
try {
   // 建立socket连接,socket是一个keep active的连接,这个方法在建立连接之前会检查是否是连接状态的。
connect();
// 用上述的socket发送数据,对于发送的数据Jredis做了一些处理
Protocol.sendCommand(outputStream, cmd, args);
pipelinedCommands++;
return this;
} catch (JedisConnectionException ex) {
/*
* When client send request which formed by invalid protocol, Redis send back error message
* before close connection. We try to read it to provide reason of failure.
*/
try {
String errorMessage = Protocol.readErrorLineIfPossible(inputStream);
if (errorMessage != null && errorMessage.length() > 0) {
ex = new JedisConnectionException(errorMessage, ex.getCause());
}
} catch (Exception e) {
/*
* Catch any IOException or JedisConnectionException occurred from InputStream#read and just
* ignore. This approach is safe because reading error message is optional and connection
* will eventually be closed.
*/
}
// Any other exceptions related to connection?
broken = true;
throw ex;
}
}

最后我们就可以通过client.getBulkReply()的方法得到响应的数据并做处理返回。

private static Object process(final RedisInputStream is) {

    final byte b = is.readByte();
if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == MINUS_BYTE) {
processError(is);
return null;
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
}

其实这个方法针对于返回的数据相应做了处理的,在我们RedisTest的测试中。返回的数据是$4 huhx。这里经过process方法的处理,只会返回huhx的数据。具体的这里不作分析。

友情链接

redis基础----->redis的基本使用(一)的更多相关文章

  1. redis基础:redis下载安装与配置,redis数据类型使用,redis常用指令,jedis使用,RDB和AOF持久化

    知识点梳理 课堂讲义 课程计划 1. REDIS 入 门 (了解) (操作)   2. 数据类型 (重点) (操作) (理解) 3. 常用指令   (操作)   4. Jedis (重点) (操作) ...

  2. 【Redis】Redis基础 - Redis安装启动测试

    Redis基本 - 安装 文章目录 Redis基本 - 安装 Linux下安装Redis Docker 方式 Github 源码编译方式 直接安装方式 Windows下Redis安装 记录 - Red ...

  3. redis 基础 Redis 数据类型

    String(字符串) Hash(哈希) List(列表) Set(集合) zset(sorted set:有序集合)

  4. mysql主从复制、redis基础、持久化和主从复制

    一.mysql(mariadb)基础 1.基础命令(centos7操作系统下) 1.启动mysql systemctl start mariadb 2.linux客户端连接自己 mysql -uroo ...

  5. linux - redis基础

    目录 linux - redis基础 redis 源码编译安装 redis 数据结构 1. strings类型 2. list 类型 3. sets集合类型 有序集合 5. 哈希数据结构 centos ...

  6. redis 基础

    一 redis数据类型redis支持5种类型的数据类型,它描述如下的:1. 字符串 Redis字符串是字节序列.Redis字符串是二进制安全的,这意味着他们有一个已知的长度没有任何特殊字符终止,所以你 ...

  7. windows下使用redis,Redis入门使用,Redis基础命令

    windows下使用redis,Redis入门使用,Redis基础命令 >>>>>>>>>>>>>>>> ...

  8. [.net 面向对象程序设计深入](14)Redis——基础

    [.net 面向对象程序设计深入](14)Redis——基础 很长一段时间没更新博客了,坚持做一件事,真不是件容易的事,后面我会继续尽可能的花时间更新完这个系列文章. 因这个系列的文章涉及的范围太大了 ...

  9. linux redis基础应用 主从服务器配置

    Redis基础应用 redis是一个开源的可基于内存可持久化的日志型,key-value数据库redis的存储分为内存存储,磁盘存储和log文件三部分配置文件中有三个参数对其进行配置 优势:和memc ...

随机推荐

  1. C语言 · 明明的随机数

    算法训练 明明的随机数   时间限制:1.0s   内存限制:256.0MB      问题描述 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的 ...

  2. 浅谈WebService的调用<转>

    0.前言 前段时间,公司和电信有个合作,产品对接电信的某个平台,使用了WebService接口的调用,实现了业务受理以及单点登录.终于使用到了WebService,楼主还是比较兴奋的,目前功能已经上线 ...

  3. Thinkphp3.2版本Controller和Action的访问方法

    一.3.2版本以前controller和action的访问方式在3.2版本以前如果Controller=c.Action=a的话,访问规则如下:http://localhost:81/demo1/in ...

  4. MySQL5.7远程连接和增加密码

    主要是5.7的很多操作和以前版本不一样,所以踩了很多坑. 1. 远程连接cant connect to mysql (10061) 一开始以为是权限问题,所以参考了详解 MySQL 5.7 新的权限与 ...

  5. 【DataStructure】Linked Data Structures

    Arrayss work well for unordered sequences, and even for ordered squences if they don't change much. ...

  6. axis client error Bad envelope tag: definitions

    http://blog.csdn.net/lifuxiangcaohui/article/details/8090503 ——————————————————————————————————————— ...

  7. *.ashx一般处理程序不能访问Session值的解决方法

    <%@ WebHandler Language="C#" Class="productHandler" %> using System; using ...

  8. zebra/quagga线程分析

    /* 线程按照不同的功能进行分类.有6条双链,分别表示不同类型的线程.将要运行的时候, * 就从不同的链表中取出,添加到ready链表中,运行完成之后,将线程结构体清空放到 * unuse链表中.一般 ...

  9. e667. 在给定图像中创建缓冲图像

    An Image object cannot be converted to a BufferedImage object. The closest equivalent is to create a ...

  10. RequireJS使用小结1——for Effective JavaScript Module Loading

    1. require和define的区别 The require() function is used to run immediate functionalities, while define() ...