话不多说,上来就是干,从头到尾来一遍,为了不依赖任何框架,直接用纯 Java Web 项目示范。
一、环境准备:
1、下载 Redis:
地址:https://github.com/MicrosoftArchive/redis/releases
我用的是 windows 系统,下载了Redis-x64-3.2.100.zip

2、安装:
解压就能用,不需要安装。
3、运行:
- 我这里将下载的文件放在了 D:\Redis 目录下,各位自行处理
- 将当前路径添加到环境变量的 path 中 (D:\Redis)
- 使用 CMD 进入相应的目录,执行 redis-server.exe 命令,
- 出现如下情形则表示Redis启动成功。
如果不添加环境变量,则需要执行 redis-server.exe redis.windows.config

** 但是这样还不够方便,可以新建一个 txt 文件 ,在里面写入 redis-server.exe(添加了环境变量)
或 redis-server.exe redis.windows.config,
然后将 txt 重命名为 bat 文件,双击运行即可

4、连接数据库:
另开一个CMD窗口
使用 redis-cli.exe -h 127.0.0.1 -p 6379 命令链接数据库,

当然这里也可以写成一个 bat 文件

但是为啥端口是 6379 呢?来自程序员的浪漫?

5、操作:
尝试向数据库中添加一个字符串类型的数据:

二、创建Java Web 工程
1、俩 jar 包:
jedis-3.0.1.jar
commons-pool2-2.6.0.jar
2、连接工具类:
import com.soft.util.ReadProperties;
import redis.clients.jedis.Jedis;
public class RedisUtil {
private static Jedis Jedis;
public static Jedis getJedis() {
if(Jedis == null) {
synchronized (RedisUtil.class) {
if(Jedis == null) {
Jedis = new Jedis(ReadProperties.getValue("Address"));
}
}
}
return Jedis;
}
}
3、读取配置文件:
import java.util.ResourceBundle;
public class ReadProperties {
public static String getValue(String str) {
String value = null;
try {
ResourceBundle resource = ResourceBundle.getBundle("config");
value = resource.getString(str);
}catch (Exception e) {
e.printStackTrace();
}
return value;
}
}
4、配置文件:
src下的config.properties

Address=localhost
5、创建 servlet :
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.soft.redis.RedisUtil;
/**
* Servlet implementation class TestJedis
*/
@WebServlet("/TestJedis")
public class TestJedis extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestJedis() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String set = RedisUtil.getJedis().set("test", "12346789");
System.err.println(set);
String string = RedisUtil.getJedis().get("test");
response.getWriter().append(" value ======> ").append(string);
}
}
6、测试:


本文详细介绍如何在Java Web项目中集成Redis,包括环境搭建、连接配置及基本操作演示。通过具体示例,读者可以快速掌握Java Web应用与Redis数据库交互的方法。
707

被折叠的 条评论
为什么被折叠?



