前言
由于当前公司进行redis缓存的地方比较多,所以公司有要自己看redis文档进行学习,在此之前,有使用过并有了解到一些redis基础知识,大部分是为了应对面试,以下是系统的笔记,方便以后复习查看.
一、Redis介绍
Redis是用C语言开发的一个开源的高性能键值对(key-value)数据库。它通过提供多种键值数据类型来适应不同场景下的存储需求,目前为止Redis支持的键值数据类型如下:
- 字符串类型
- 散列类型
- 列表类型
- 集合类型
- 有序集合类型
1)应用场景
1.缓存使用最多(数据查询、短连接、新闻内容、商品内容等)
2.分布式集群架构中的session分离
3.聊天室的在线好友列表
4.任务队列(秒杀、抢购、12306等等)
5.应用排行榜
6.网站访问统计
7.数据过期处理(可以精确到毫秒)
二、Redis在Linux上安装
-
Linux安装:https://blog.csdn.net/Makasa/article/details/99758838
-
如果是在Windows上面安装去官网下载一个,解压即可
三、Java客户端Jedis
Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。 在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用Jedis和Redisson。 在企业中用的最多的就是Jedis
1、基本使用
1)添加jar包
2)单实例连接
@Test
public void testJedis() {
jedis.select(1);//设置数据库
//创建一个Jedis的连接
Jedis jedis = new Jedis("127.0.0.1", 6379);
//执行redis命令
jedis.set("mytest", "hello world, this is jedis client!");
//从redis中取值
String result = jedis.get("mytest");
//打印结果
System.out.println(result);
//关闭连接
jedis.close();
}
3)连接池连接
@Test
public void testJedisPool() {
//创建一连接池对象
JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
//从连接池中获得连接
Jedis jedis = jedisPool.getResource();
String result = jedis.get("mytest");
System.out.println(result);
//关闭连接
jedis.close();
//关闭连接池
jedisPool.close();
}
2、Spring整合jedisPool
-
添加spring的jar包
-
配置spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
ht