redis基础----->redis的基本使用(一)
这里我们就在虚拟机中安装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的基本使用(一)的更多相关文章
- redis基础:redis下载安装与配置,redis数据类型使用,redis常用指令,jedis使用,RDB和AOF持久化
知识点梳理 课堂讲义 课程计划 1. REDIS 入 门 (了解) (操作) 2. 数据类型 (重点) (操作) (理解) 3. 常用指令 (操作) 4. Jedis (重点) (操作) ...
- 【Redis】Redis基础 - Redis安装启动测试
Redis基本 - 安装 文章目录 Redis基本 - 安装 Linux下安装Redis Docker 方式 Github 源码编译方式 直接安装方式 Windows下Redis安装 记录 - Red ...
- redis 基础 Redis 数据类型
String(字符串) Hash(哈希) List(列表) Set(集合) zset(sorted set:有序集合)
- mysql主从复制、redis基础、持久化和主从复制
一.mysql(mariadb)基础 1.基础命令(centos7操作系统下) 1.启动mysql systemctl start mariadb 2.linux客户端连接自己 mysql -uroo ...
- linux - redis基础
目录 linux - redis基础 redis 源码编译安装 redis 数据结构 1. strings类型 2. list 类型 3. sets集合类型 有序集合 5. 哈希数据结构 centos ...
- redis 基础
一 redis数据类型redis支持5种类型的数据类型,它描述如下的:1. 字符串 Redis字符串是字节序列.Redis字符串是二进制安全的,这意味着他们有一个已知的长度没有任何特殊字符终止,所以你 ...
- windows下使用redis,Redis入门使用,Redis基础命令
windows下使用redis,Redis入门使用,Redis基础命令 >>>>>>>>>>>>>>>> ...
- [.net 面向对象程序设计深入](14)Redis——基础
[.net 面向对象程序设计深入](14)Redis——基础 很长一段时间没更新博客了,坚持做一件事,真不是件容易的事,后面我会继续尽可能的花时间更新完这个系列文章. 因这个系列的文章涉及的范围太大了 ...
- linux redis基础应用 主从服务器配置
Redis基础应用 redis是一个开源的可基于内存可持久化的日志型,key-value数据库redis的存储分为内存存储,磁盘存储和log文件三部分配置文件中有三个参数对其进行配置 优势:和memc ...
随机推荐
- [DNS]部署局域网DNS服务器
This is a step by step tutorial on how to install and configure DNS server for your LAN using bind9. ...
- JavaScript 深入理解作用域链
第一步. 定义后:每个已定义函数,都有一个内在属性[scope],其对应一个对象的列表,列表中的对象仅能内部访问. 例如:建立一个全局函数A,那么A的[Scope]内部属性中只包含一个全局对象(Glo ...
- uboot中DEBUG定义
uboot的debug定义在include/common.h中 #ifdef DEBUG #define debug(fmt, args...) printf(fmt, ##args) #defin ...
- Hive Tuning(四) 从查询计划看hive.auto.convert.join的好处
今天我们来讲一下如何看懂Hive的查询计划. hive的执行计划包括三部分 – Abstract syntax tree – 可以直接忽略 – Stage dependencies – 依赖 – S ...
- RTMP规范 消息与消息块
Real Time Messaging Protocol(实时消息传输协议) 应用层协议 RTMP协议中, 基本数据单元称为消息(Message).当RTMP协议在互联网中传输数据的时候,消息会被拆分 ...
- Linux 精确获取指定目录对应的块的剩余空间
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/statfs ...
- 在 PL/SQL 块的哪部分可以对初始变量赋予新值? (选择1项)
A.结尾部分 B.开头部分 C.执行部分 D.声明部分 解答:C
- opencv实例三:播放AVI格式视频
一.不带滚动条的视频读取播放. 1.原理介绍:视频的本质是一些静态的图像的集合,opencv可以不断读取视屏中的图片,显示,就可以实时的视频流进行处理了. 2.代码如下: /************* ...
- CentOS 6.5在grub界面下更改root密码
想要更改CentOS 7 root的密码或者忘记了root的密码的时候可以在grub界面下更改root的密码. 百度了很多内容,更多方法都是适用于centos6及以前版本的,终于找到一个可以的. 1. ...
- shiro+spring相关配置
首先pom中添加所需jar包: <!-- shiro start --> <dependency> <groupId>org.apache.shiro</gr ...