java操作Redis
Jedis简介实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis,对于主流语言,Redis都提供了对应的客户端;提供了很多客户端 官方推荐的是Jedis托管地址:https://github.com/xetorthio/jedis要使用redis首先得下载pom依赖<dependency><groupId>redis.cl...
·
Jedis简介
实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis,
对于主流语言,Redis都提供了对应的客户端;
提供了很多客户端 官方推荐的是Jedis 托管地址:https://github.com/xetorthio/jedis
要使用redis首先得下载pom依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
连接redis
Jedis jedis = new Jedis("192.168.221.131", 6379); //指定Redis服务Host和port
jedis.auth("root"); //如果Redis服务连接需要密码,制定密码
String value = jedis.get("key"); //访问Redis服务
jedis.close(); //使用完关闭连
System.out.println(jedis.ping());
使用Jedis连接池之后,在每次用完连接对象后一定要记得把连接归还给连接池。Jedis对close方法进行了改造,如果是连接池中的连接对象,调用Close方法将会是把连接对象返回到对象池,若不是则关闭连接。
操作Redis常用的三种数据类型 ,还有两种不常用的就不介绍了
// 操作字符串
// jedis.set("aaa","zs");
// System.out.println(jedis.get("aaa"));
// 操作哈希
// jedis.hset("user1","uname3","qq");
// jedis.hset("user1","uname4","zl");
// System.out.println(jedis.hgetAll("user1"));
// System.out.println(jedis.hget("user1", "uname3"));
// 操作列表
//
// jedis.lpush("hobby","a","b","c","d","f");
// lpop 从下往上弹栈 rpop 从上往下弹栈
// System.out.println(jedis.lpop("hobby"));
// System.out.println(jedis.lpop("hobby"));
// System.out.println(jedis.rpop("hobby"));
Demo1
package com.tzp;
import redis.clients.jedis.Jedis;
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 java.io.IOException;
import java.util.Map;
/**
* @author 心如止水
* @site www.xiaomage.com
* @company
* @create 2019-09-19 15:41
*/
@WebServlet("/getDate")
public class DemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 首页第一次是读取数据库,后面读取缓存(在没有增删改的情况)
// 首先从缓存中去拿数据
Jedis jedis = new Jedis("192.168.221.131", 6379);
jedis.auth("root");
// 从缓存中获取当前登录的用户信息
Map<String, String> currentUser = jedis.hgetAll("currentUser");
if(currentUser !=null && currentUser.size()>0){
req.setAttribute("msg","从缓存中拿到shuju");
}
else{
// 第一次登录,第一次访问首页数据
req.setAttribute("msg","我是从缓存中拿到数据");
String uname = "tanqi";
String upass = "123456";
// 接下来的把数据中对应的对象存储到保存缓存中
jedis.hset("currentUser","uname3","tanqi");
jedis.hset("currentUser","uname3","123456");
// 此时能获取到值原因是上面已经讲数据存储到缓存中
currentUser = jedis.hgetAll("currentUser");
req.setAttribute("currentUser",currentUser);
}
req.getRequestDispatcher("/home.jsp").forward(req,resp);
}
}
jsp
<%--
Created by IntelliJ IDEA.
User: a
Date: 2019/9/19
Time: 15:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored= "false"%>
<html>
<head>
<title>Title</title>
</head>
<body>
博客首页
拿去数据的方式:${msg}<br>
拿到的数据${currentUser}
</body>
</html>
第一次访问
第二次访问
第一次访问时是直接读数据库,后面都是进缓存拿数据
public String list() {
try {
HttpServletRequest request = ServletActionContext.getRequest();
if (StringUtils.isBlank(title)) {
String blogListJsonStr = jedis.get("blogList");
//如果redis中有值
if(blogListJsonStr!= null && blogListJsonStr.length() > 0) {
// 使用redis
request.setAttribute("blogList", JSON.parse(blogListJsonStr));
}else {
//使用数据库
//从数据库中查询数据
List<Map<String, Object>> blogList = this.blogDao.freemarker_list(title, null);
//放进缓存
jedis.set("blogList", JSON.toJSONString(blogList));
//存作用域
request.setAttribute("blogList", blogList);
}
}else {
Directory directory = LuceneUtil.getDirectory(PropertiesUtil.getValue("indexPath"));
DirectoryReader reader = LuceneUtil.getDirectoryReader(directory);
IndexSearcher searcher = LuceneUtil.getIndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
// 拿一句话到索引目中的索引文件中的词库进行关键词碰撞
Query query = new QueryParser("title", analyzer).parse(title);
Highlighter highlighter = LuceneUtil.getHighlighter(query, "title");
TopDocs topDocs = searcher.search(query , 100);
//处理得分命中的文档
List<Map<String, Object>> blogList = new ArrayList<>();
Map<String, Object> map = null;
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
map = new HashMap<>();
Document doc = searcher.doc(scoreDoc.doc);
map.put("id", doc.get("id"));
String titleHighlighter = doc.get("title");
if(StringUtils.isNotBlank(titleHighlighter)) {
titleHighlighter = highlighter.getBestFragment(analyzer, "title", titleHighlighter);
}
map.put("title", titleHighlighter);
map.put("url", doc.get("url"));
blogList.add(map);
}
request.setAttribute("blogList", blogList);
}
} catch (Exception e) {
e.printStackTrace();
}
return "blogList";
}
实现增删查改
public String add() {
HttpServletRequest request = ServletActionContext.getRequest();
Map<String,String[]> parameterMap = request.getParameterMap();
try {
//清空缓存
jedis.del("blogList");
//加入数据库
this.blogDao.save(parameterMap);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "blogList";
}
public String del() {
try {
HttpServletRequest request = ServletActionContext.getRequest();
//清空缓存
jedis.del("blogList");
// 数据库中删除博客
this.blogDao.del(request.getParameterMap());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "blogList";
}
public String edit() {
HttpServletRequest request = ServletActionContext.getRequest();
Map parameterMap = request.getParameterMap();
try {
// 修改数据库中的值
this.blogDao.edit(request.getParameterMap());
//清空缓存
jedis.del("blogList");
// 修改lucene中的文档值
IndexWriter writer = getIndexWriter();
Document doc = new Document();
doc.add(new StringField("id", JsonUtils.getParamVal(parameterMap, "bid"), Field.Store.YES));
doc.add(new StringField("bid", JsonUtils.getParamVal(parameterMap, "bid"), Field.Store.YES));
doc.add(new TextField("title", JsonUtils.getParamVal(parameterMap, "title"), Field.Store.YES));
doc.add(new TextField("summary", JsonUtils.getParamVal(parameterMap, "summary"), Field.Store.YES));
writer.updateDocument(new Term("id", JsonUtils.getParamVal(parameterMap, "bid")), doc);
writer.close();
// 修改静态页(相同id会之间覆盖)
addStaticPage(JsonUtils.getParamVal(parameterMap, "bid"), parameterMap);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return "blogList";
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)