前提:
开始在 Java 中使用 Redis 前, 我们需要确保已经安装了redis服务端及Java redis 驱动,且能正常使用 Java。
安装 Java redis 驱动
下载驱动包 jedis.jar (https://mvnrepository.com/artifact/redis.clients/jedis) ,下面是下载方法,一般都是下载最新的jar包(jedis-2.9.0.jar)
下载完成后,将该jar包放在 classpath(也就是tomcat中lib下) 路径里面。
备注:
有的时候只有jedis这一个jar包还不够,还需要
jedis-2.5.2.jar
下载地址:https://mvnrepository.com/artifact/redis.clients/jedis
tomcat-redis-session-manager-VERSION.jar
下载地址:http://www.vdisk.cn/tomcatredissessionmanager/19397609.html
commons-pool2-2.2.jar
下载地址:http://commons.apache.org/proper/commons-pool/download_pool.cgi
整体下载链接地址:https://pan.baidu.com/s/1jJul9kE
配置tomcat
修改tomcat/conf/context.xml文件,在最后一个 < /Context>上边添加 如下代码:
<ValveclassNameValveclassName="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve"/>
<ManagerclassNameManagerclassName="com.orangefunction.tomcat.redissessions.RedisSessionManager"
host="192.168.133.2" <!—redis的ip地址-->
port="6379"
database="0"
maxInactiveInterval="60"/>
测试和服务器端的连接
import redis.clients.jedis.Jedis;
public class RedisJava {
public static void main(String[] args) {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("连接成功");
//查看服务是否运行
System.out.println("服务正在运行: "+jedis.ping());
}
}
编译以上 Java 程序,确保驱动包的路径是正确的。
输出:
连接成功
服务正在运行: PONG