java 操作 Redis

基礎操作

Demo1

package com.lst;

import redis.clients.jedis.Jedis;

/**
 * @create 2019-09-18 13:45
 *
 * 講解是Java代碼去操作Redis
     * 鏈接Redis
     * 操作字符串
     * 操作哈希
     * 操作列表
 */
public class Demo1 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.146.128",6379);
        jedis.auth("123456");
//        System.out.println(jedis.ping());

//        操作字符串
//        jedis.set("aaa","zs");
//        System.out.println(jedis.get("aaa"));

//        操作哈希
//        jedis.hset("user1","uname","ls");
//        jedis.hset("user1","sex","人妖");

//        System.out.println(jedis.hgetAll("user1"));
//        System.out.println(jedis.hget("user1", "uname"));

//        操作列表
        jedis.lpush("hobby","a","b","c","d","e");
        System.out.println(jedis.lpop("hobby"));
        System.out.println(jedis.lpop("hobby"));
        System.out.println(jedis.rpop("hobby"));

    }
}

在這裏插入圖片描述
DemoServlet

package com.lst;

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;

/**
 * @create 2019-09-18 14:19
 */
@WebServlet("/getData")
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.146.128",6379);
        jedis.auth("123456");
//        從緩存中獲取當前登錄的用戶信息
        Map<String, String> currentUser = jedis.hgetAll("currentUser");
        if(currentUser != null && currentUser.size()>0){
            req.setAttribute("msg","從緩存中獲取數據");
            req.setAttribute("currentUser",currentUser);
            System.out.println("aaa");
        }
        else{
            System.out.println("bbb");
//            第一次登錄,第一次訪問首頁數據
            req.setAttribute("msg","從數據庫中獲取數據");
            String uname = "tianqi";
            String upass = "123456";
//            接下來把數據中的對應對象存儲到緩存中
            jedis.hset("currentUser","uname","tianqi");
            jedis.hset("currentUser","upass","123456");
//            此時能回去到值原因是上面已經將數據存儲到緩存中
            currentUser = jedis.hgetAll("currentUser");
            req.setAttribute("currentUser",currentUser);
        }
        req.getRequestDispatcher("/home.jsp").forward(req,resp);
    }
}

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/9/18 0018
  Time: 14:19
  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>

在這裏插入圖片描述

實踐

在lunece和頁面靜態化的基礎上,我們可以進行優化。
當我們第一次登錄的時候,首先要進入數據庫查數據,然後生成緩存文件。如果下一次我們在數據沒有進行增刪改的情況下,我們可以直接調用緩存文件。
當數據發生改變的時候 ,也就是進行了增刪改。我們就要順帶更新緩存,下一次再次訪問首頁要保證redis中數據跟mysql數據是一致

先導入pom依賴

<!-- Redis -->
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.9.0</version>
</dependency>

BlogAction

	private static String host = "192.168.146.128"; //連接的IP地址
	
	public static Jedis jedis() {
		Jedis jedis = new Jedis(host, 6379);
		jedis.auth("123456");// 權限認證
		jedis.ping();//判斷是否連接成功(成功pong)
		jedis.select(2);// 切換數據庫
		return jedis;
	}

	public String list() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			Map<String, String[]> parameterMap = request.getParameterMap();
			if (StringUtils.isBlank(title)) {
				//連接Redis
				Jedis jedis = jedis();
				//獲取緩存數據
				String blogList = jedis.get("blogList");
				String blogzt = jedis.get("blogzt");
				
				if(blogList != null && blogzt == null) {//當Redis中有數據,
					//直接從緩存中獲取數據
					blogList = jedis.get("blogList");
					System.out.println("從緩存中獲取數據");
				}
				else {//當Redis中沒有數據的時候
					//從數據庫中獲取數據出來
					List<Map<String, Object>> list = this.blogDao.list(title, null);
					//放入Redis中
					jedis.set("blogList", JSON.toJSONString(list));
					
					//拿取值
					blogList = jedis.get("blogList");
					
					//清除狀態
					jedis.del("blogzt");
					
					System.out.println("從數據庫中獲取數據");
					
					
					
				}
				request.setAttribute("blogList", JSON.parse(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() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException,
			IllegalArgumentException, SQLException {
		HttpServletRequest req = ServletActionContext.getRequest();
		Map<String, String[]> paMap = req.getParameterMap();
		System.out.println(title + "tit");
		int save = blogDao.save(paMap);
		// 數據增加成功,同時增加索引
		if (save > 0) {
			//連接Redis
			Jedis jedis = jedis();
			//改變state狀態
			jedis.set("blogzt", "1");
			
			System.out.println("增加成功");
			// 新增索引
			IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
			Directory d;
			IndexWriter indexWriter = null;
			try {
				d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
				indexWriter = new IndexWriter(d, conf);
				Document doc = new Document();
				doc.add(new StringField("id", id, Field.Store.YES));
				doc.add(new TextField("title", title, Field.Store.YES));
				doc.add(new TextField("content", content, Field.Store.YES));
				doc.add(new StringField("url", url, Field.Store.YES));
				indexWriter.addDocument(doc);
				System.out.println("添加索引成功");
				// 新增靜態頁面
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "blogList";
		} else {
			System.out.println("增加失敗");
			return "blogList";
		}
	}

	/**
	 * 
	 * 刪除指定索引庫中 指定域(fieldName) 包含指定字符串(text) 的索引
	 * 
	 * @return
	 * @throws IOException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws SQLException
	 */
	public String del() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException,
			SecurityException, IllegalArgumentException, SQLException {
		HttpServletRequest req = ServletActionContext.getRequest();
		int del = blogDao.del(req.getParameterMap());
		if (del > 0) {
			//連接Redis
			Jedis jedis = jedis();
			//改變state狀態
			jedis.set("blogzt", "1");
			
			System.out.println("刪除成功");
			IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
			Directory d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
			IndexWriter indexWriter = new IndexWriter(d, conf);
			// Term:表示詞元,第一個參數:域名, 第二個參數:要刪除含有此關鍵詞的數據
			// deleteDocuments(Term... terms):可以同時根據多個詞元進行刪除
			Term term1 = new Term("id", id);
			Term term2 = new Term("title", title);
			Term term3 = new Term("content", content);
			Term term4 = new Term("url", url);
			indexWriter.deleteDocuments(term1, term2, term3, term4);

			System.out.println("刪除索引成功");
			return "blogList";
		} else {
			System.out.println("刪除失敗");
			return "blogList";
		}
	}	

第一次是從數據庫中取出數據
第二次是從緩存中獲取數據
對數據進行增刪改後,第一次是從數據庫獲取的數據
在這裏插入圖片描述
over。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章