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 ...
随机推荐
- HAProxy+Varnish+LNMP实现高可用负载均衡动静分离集群部署
HAProxy高可用负载均衡集群部署 基本信息: 系统平台:VMware WorkStation 系统版本: CentOS Linux release 7.2.1511 (Core) 内核版本: 3. ...
- oozie中使用sqoop导入hive表时提示hive找不到
根据出错信息是找不到hive的位置,所以想到的解决方法是: 在sqoop的workflow中添加job-xml,属性写hive-site.xml在hdfs上的位置. (fail) 直接配置一个hive ...
- (转) eclipse安装lombok
lombok的官方网址:http://projectlombok.org/ 1. lombok的安装: 使用lombox是需要安装的,如果不安装,IDE则无法解析lombox注解,有两种方式可以安装l ...
- Java NIO使用及原理分析(二)(转)
在第一篇中,我们介绍了NIO中的两个核心对象:缓冲区和通道,在谈到缓冲区时,我们说缓冲区对象本质上是一个数组,但它其实是一个特殊的数组,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况,如 ...
- 常见JVM监控工具用法介绍
VisualVM是一种集成了多个JDK命令行工具的可视化工具,它能为您提供强大的分析能力.所有这些都是免费的!它囊括的命令行工具包括jps,jstat,jmap,jinfo,jstack,JConso ...
- CentOS6.5下安装Cloudstack
个人记录: 使用yum源安装,地址:http://mirrors.163.com/.help/CentOS6-Base-163.repo 后续待进行
- hdu3065 病毒侵袭持续中 AC自动机入门题 N(N <= 1000)个长度不大于50的模式串(保证所有的模式串都不相同), 一个长度不大于2000000的待匹配串,求模式串在待匹配串中的出现次数。
/** 题目:hdu3065 病毒侵袭持续中 链接:http://acm.hdu.edu.cn/showproblem.php?pid=3065 题意:N(N <= 1000)个长度不大于50的 ...
- [转]解决eclipse无法设置NDK问题
参考:http://jingyan.baidu.com/album/4d58d5413000a09dd4e9c0fe.html?picindex=1 到android sdk官网下载r23版本的ad ...
- js本地图片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- PHP变量解析顺序variables_order
转载自:http://blog.csdn.net/knight0450/article/details/4291556 故事从一个有点诡异的BUG开始,后台一个使用频率不是很高的广告提交功能有时候会莫 ...