Redis安装部署、Jedis的使用

时间:2023-03-09 02:29:25
Redis安装部署、Jedis的使用

一、NoSQL概述

为什么需要NoSQL

  • High performance -高并发读写
  • Huge Storage - 海量数据的高效率存储和访问
  • High Scalability && High Availability -高扩展性和高可用性

NoSQL的特点

  • 易扩展
  • 大数据量,高性能
  • 灵活的数据类型
  • 高可用

二、Redis概述

高性能键值对数据库,支持的键值数据类型:

  • 字符串类型
  • 列表类型
  • 有序集合类型
  • 散列类型
  • 集合类型

Redis的应用场景

  • 缓存
  • 任务列表
  • 应用排行榜
  • 网站访问统计
  • 数据过期处理
  • 分布式集群架构中的session分离

Redis的安装

搭建环境

  • 虚拟机:VMware 10.0.2
  • Linnux系统:CentOS-6.5
  • SSH客户端:SecureCRT 7.3,SecureFX 7.3

搭建步骤

  1. Linx在线安装gcc >yum install gcc-c++
  2. 解压文件 >tar -axvf redis.tar.gz
  3. 进入Redis目录进行编译:make
  4. 安装 make PREFIX=/usr/local/redis install
  5. 将解压的redis文件夹里的redis.conf 复制到 redis安装目录下cp redis.conf  /usr/local/redis
  6. 编辑redis.conf配置文件,修改daemonize选项的值为yes
  7. 进入redis安装目录下运行redis ./bin/redis-server ./redis.conf
  8. ps -ef | grep -i redis 查看redis进程
  9. 关闭redis ./bin/redis-cli shutdown
  10. 打开redis客户端命令行 ./bin/redis -cli

三、Jedis入门

  • Jedis是Redis 官方首选的Java客户端开发包
  • http://github.com/xetorthio/jedis

Jedis开发流程

  • 引入依赖

Redis安装部署、Jedis的使用

  • 编辑Linux系统的网络配置文件
vim /etc/sysconfig/iptables
  • 加入下列指令,打开把6379端口
-A INPUT -p tcp -m state --state NEW -m tcp --dport 6379 -j ACCEPT
  • 重启防火墙服务
service iptables restart

测试代码

@Test
public void demo1(){
//1.设置IP地址和端口
Jedis jedis = new Jedis("192.168.61.128",6379);
System.out.println(jedis.ping());
//2.保存数据
jedis.set("school", "nchu");
//获取数据
String value = jedis.get("school");
System.out.print(value);
}

注意事项

  • 错误

redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refuse: connect

  • 解决办法

1.修改配置文件redis.conf,将bind注释掉,允许外面的机器连接

Redis安装部署、Jedis的使用

2.修改配置文件redis.conf,将protected mode 的值改为no,关闭保护模式,并重新启动redis服务

Redis安装部署、Jedis的使用

测试运行,控制台输出

PONG
nchu