-
在pom.xml中下載redis的依賴
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
-
連接數據庫
//輸入你的ip和 端口 Jedis jedis = new Jedis("192.168.80.128",6379); jedis.auth("613613"); //設置的密碼 System.out.println(jedis.ping());
效果:
-
操作字符串
jedis.set("ht","牆頭馬上遙相顧");
在客戶端中查看
System.out.println( jedis.get("ht"));
服務端測試查看
-
操作哈希
jedis.hset("user","uname","黃大娘");
edis.hset("user","usex","女");
效果
在服務端查看
//得到哈希值 System.out.println(jedis.hgetAll("user")); //方式一 System.out.println(jedis.hget("user", "uname"));
-
操作列表
jedis.lpush("shici","青燈","不歸客","山有木兮","木有之","牆頭","馬上");
效果
服務端測試
System.out.println(jedis.lpop("shici"));//桟結構,所以是先進后出的道理
- 模擬數據存在redis緩存中
HuangSevlet
package com.huang; 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 黃大娘 * @company dogson有限公司 * @create 2019-09-18 15:46 */ @WebServlet("/gethuang") public class HuangServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //第一次讀取數據庫,后從緩存中讀取數據 Jedis jedis = new Jedis("192.168.80.128",6379); jedis.auth("613613"); //從緩存中讀取用戶 Map cretauser =jedis.hgetAll("cretauser"); if (cretauser !=null && cretauser.size()>0 ){ req.setAttribute("msg","從緩存中拿數據"); }else{ //第一次登陸獲取首頁數據 req.setAttribute("msg","從數據庫中拿數據"); String uname="huangting"; String upas="123456"; //把數據庫中對應的對象存到緩存中 jedis.hset("cretauser","uname","huangting"); jedis.hset("cretauser","upas","123456"); cretauser = jedis.hgetAll("cretauser"); req.setAttribute("cretauser",cretauser); } req.getRequestDispatcher("/index.jsp").forward(req,resp); } }
優化項目
第一次去數據庫中拿數據后期在從Redis緩存中拿數據,減少訪問數據庫的次數提高性能
package com.huangting.blog.web; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.file.Paths; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.highlight.Formatter; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.Parameter.Request; import com.huangting.blog.dao.BlogDao; import com.huangting.blog.util.JsonUtils; import com.huangting.blog.util.LuceneUtil; import com.huangting.blog.util.PropertiesUtil; import com.huangting.blog.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * 專門將網頁靜態化的類,這里不涉及到lucene * @author Administrator * */ public class FreemarkerBlogAction { private String title; private String bid; private BlogDao blogDao = new BlogDao(); private static Jedis jedis; static { jedis =new Jedis("192.168.80.128",6379); jedis.auth("613613"); jedis.select(0); //選擇要操作的數據庫 } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBid() { return bid; } public void setBid(String bid) { this.bid = bid; } public String list() { try { HttpServletRequest request = ServletActionContext.getRequest(); if (StringUtils.isBlank(title)) { // 從Redis中獲取數據 String bolgListALL =jedis.get("blogList"); if(bolgListALL != null && bolgListALL.length()>0) { System.out.println("使用redis緩存查詢"); request.setAttribute("blogList", JSON.parse(bolgListALL)); }else { // 從數據庫中查詢數據 List<Map<String, Object>> blogList = this.blogDao.freemarker_list(title, null); // 放入緩存 jedis.set("blogList", JSON.toJSONString(blogList)); //傳到jsp頁面 request.setAttribute("blogList", blogList); System.out.println("從數據中拿數據"); } } else { SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer(); IndexReader indexReader = DirectoryReader .open(FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")))); IndexSearcher searcher = new IndexSearcher(indexReader); // 拿一句話到索引目中的索引文件中的詞庫進行關鍵詞碰撞 Query query = new QueryParser("title", analyzer).parse(title); TopDocs topDocs = searcher.search(query, 100); // 將碰撞出來的關鍵詞給點亮 QueryScorer queryScorer = new QueryScorer(query); // 以什么形式點亮關鍵詞 Formatter formatter = new SimpleHTMLFormatter("<span style='color:red;'><b>", "</span></b>"); Highlighter highlighter = new Highlighter(formatter, queryScorer); 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("bid", doc.get("bid")); map.put("summary", doc.get("summary")); String titleHighlighter = doc.get("title"); if (StringUtils.isNotBlank(titleHighlighter)) { titleHighlighter = highlighter.getBestFragment(analyzer, "title", titleHighlighter); } map.put("title", titleHighlighter); blogList.add(map); } indexReader.close(); request.setAttribute("blogList", blogList); } } catch (Exception e) { e.printStackTrace(); } return "blogList"; } /** * 這是刷新全局索引調用的方法 * * @return */ public String refreshIndex() { IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer()); Directory d; IndexWriter indexWriter = null; try { // 先將索引庫中的索引文件清空 delTempChild(new File(PropertiesUtil.getValue("indexPath"))); d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath"))); indexWriter = new IndexWriter(d, conf); List<Map<String, Object>> list = blogDao.freemarker_list(null, null); for (Map<String, Object> map : list) { Document doc = new Document(); doc.add(new StringField("id", String.valueOf(map.get("bid")), Field.Store.YES)); doc.add(new StringField("bid", String.valueOf(map.get("bid")), Field.Store.YES)); doc.add(new TextField("title", (String) map.get("title"), Field.Store.YES)); doc.add(new TextField("summary", (String) map.get("summary"), Field.Store.YES)); indexWriter.addDocument(doc); } } catch (IOException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (indexWriter != null) { indexWriter.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "blogList"; } public void delTempChild(File file) { if (file.isDirectory()) { String[] children = file.list();// 獲取文件夾下所有子文件夾 // 遞歸刪除目錄中的子目錄下 for (int i = 0; i < children.length; i++) { delTempChild(new File(file, children[i])); } } // 目錄空了,進行刪除 file.delete(); } /** * 修改前期 * * @return */ public String perEidt() { HttpServletRequest request = ServletActionContext.getRequest(); try { Map<String, Object> map = this.blogDao.getBlogById(bid); request.setAttribute("map", map); } catch (InstantiationException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "blogEdit"; } /** * 添加博客 * * @return * @throws SQLException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws SecurityException * @throws NoSuchFieldException */ public String add() { HttpServletRequest request = ServletActionContext.getRequest(); Map parameterMap = request.getParameterMap(); try { // 將博客添加到數據庫中 this.blogDao.add(parameterMap); //清除Redis緩存 jedis.del("blogList"); // 獲取當前博客的id int maxId = (int) this.blogDao.maxId(); // 添加到lucene 索引庫中 addIndex(maxId + "", parameterMap); // 將這篇博客進行網頁靜態化 addStaticPage(maxId + "", parameterMap); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "blogList"; } /** * 這是刪除博客的方法 */ public String del() { HttpServletRequest request = ServletActionContext.getRequest(); Map parameterMap = request.getParameterMap(); try { // 數據庫中刪除博客 this.blogDao.del(request.getParameterMap()); //清除Redis緩存 jedis.del("blogList"); // 刪除lucene中對應的文檔 IndexWriter indexWriter = getIndexWriter(); indexWriter.deleteDocuments(new Term("id", bid)); indexWriter.forceMergeDeletes(); // 強制刪除 indexWriter.commit(); indexWriter.close(); // 刪除頁面 new File("F:\\java2\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker" + bid + ".html").delete(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return "blogList"; } /** * 這是修改的方法 * * @return */ public String edit() { HttpServletRequest request = ServletActionContext.getRequest(); Map parameterMap = request.getParameterMap(); try { // 修改數據庫中的值 this.blogDao.edit(request.getParameterMap()); //清除Redis緩存 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"; } /** * 獲取寫入對象 * * @return * @throws IOException */ public IndexWriter getIndexWriter() throws IOException { IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer()); Directory d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath"))); return new IndexWriter(d, conf); } /** * 添加索引文件 * * @param id * @param parameterMap * @throws IOException */ private void addIndex(String id, Map parameterMap) throws IOException { IndexWriter indexWriter = getIndexWriter(); Document doc = new Document(); doc.add(new StringField("id", id, Field.Store.YES)); doc.add(new StringField("bid", id, 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)); indexWriter.addDocument(doc); indexWriter.close(); } /** * 這是添加靜態頁 * * @throws IOException * @throws TemplateException */ public void addStaticPage(String id, Map parameterMap) throws IOException, TemplateException { // 1.創建配置類 Configuration configuration = new Configuration(Configuration.getVersion()); // 2.設置模板所在的目錄 configuration.setDirectoryForTemplateLoading( new File("F:\\java2\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker")); // 3.設置字符集 configuration.setDefaultEncoding("utf-8"); // 4.加載模板 (這是在 剛剛設置好的 目錄下面去找) Template template = configuration.getTemplate("blogDetail.ftl"); Map map = new HashMap<>(); Map<String, Object> blog = new HashMap<>(); blog.put("bid", id); blog.put("title", JsonUtils.getParamVal(parameterMap, "title")); blog.put("releaseDate", new Date()); blog.put("btid", JsonUtils.getParamVal(parameterMap, "btid")); blog.put("clickHit", JsonUtils.getParamVal(parameterMap, "clickHit")); blog.put("content", JsonUtils.getParamVal(parameterMap, "content")); map.put("blog", blog); // // 6.創建Writer對象 Writer out = new FileWriter( new File("F:\\java2\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker" +blog.get("bid") + ".html")); // 7.輸出 template.process(map, out); // 8.關閉Writer對象 out.close(); } }
運行速度快了蠻多
謝謝觀看!