使用Java代码操作Redis

使用Java代码操作Redis

基础操作

增加maven 依赖

http://maven.outofmemory.cn/redis.clients/jedis/2.6.1/

  • 首先,我们导入依赖:
 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
  • 操作简单案例
package com.lin;

import redis.clients.jedis.Jedis;

/**
 * @authorlinfan
 * @create  2019-09-18 16:18
 * 讲解Java就代码去操作redis
     * 链接redis
     * 操作字符串
     * 操作哈希
     * 操作列表list
     * 操作set集合
     * zset(sorted set:有序集合)
 */
public class Demo1 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.133.128",6379);
        jedis.auth("123456");
        System.out.println(jedis.ping());

        //操作字符串
//        jedis.set("name","zg");//存
//        System.out.println(jedis.get("name"));//取

        //操作哈希
//        jedis.hset("user1","uname","gg");
//        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","f");
        System.out.println(jedis.lpop("hobby"));//取最上面的
        System.out.println(jedis.lpop("hobby"));//若重复使用,则取下一个
        System.out.println(jedis.rpop("hobby"));//取最下面的

    }
}

简单案例

  • 当我们查数据时,可以利用redis。第一次查询查询数据库,然后将数据放入redis中,之后的数据就直接从redis中获取
  1. 首页第一次是读取数据库,后面读取缓存(在没有增删改的情况)
  2. 增删改的时候,要顺带更新缓存,下一次再次访问首页要保证redis中数据跟mysql数据是一致
  • DemoServlet.java
package com.lin;

import javax.jws.WebService;
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;

/**
 * @authorlinfan
 * @site www.linfanmage.com
 * @company xxx公司
 * @create  2019-09-18 16:59
 *
 */
@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 {
        // 1、首页第一次是读取数据库,后面读取缓存(在没有增删改的情况)
        Jedis jedis = new Jedis("192.168.133.128",6379);
        jedis.auth("123456");
        //从缓存中获取当前登录的用户信息
        Map<String, String> currentUser = jedis.hgetAll("currentUser");
        if (classurrentUser !=null && currentUser.size()>0){
            req.setAttribute("msg","从缓存中获取数据");
//                       展示到页面的值,${xxx}
            req.setAttribute("currentUser",currentUser);
        }else{
//            第一次登录,第一次访问首页数据
            req.setAttribute("msg","从数据库中获取数据");
            String uname = "tianqi";
            String upass = "123456";
//            接下来把数据中的对应对象存储到缓存中
            jedis.hset("currentUser","uname","tianqi");
            jedis.hset("currentUser","upass","123456");
//            此时能获取到值的原因是上面已经将数据存储到缓存中
            currentUser = jedis.hgetAll("currentUser");
//            展示到页面的值,${xxx}
            req.setAttribute("currentUser",currentUser);
        }
        req.getRequestDispatcher("/home.jsp").forward(req,resp);
    }
}
  • 第一次执行效果
    在这里插入图片描述
  • 第二次执行
    在这里插入图片描述

redis 实战

  • 这里只需要在 FreemarkerBlogAction 中修改一小部分代码就可以优化整体性能啦。
    FreemarkerBlogAction
public class FreemarkerBlogAction {
	private String title;
	private String bid;
	private BlogDao blogDao = new BlogDao();
	//	这是维持redis客户端连接
	private static Jedis jedis;
	
	static {
		//初始化缓存信息
		jedis = new Jedis("192.168.133.128",6379);
		jedis.auth("root");
		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;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	public String list() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			if (StringUtils.isBlank(title)) {
				//从redis中获取数据
				String blogListJsonStr = jedis.get("blogList");
				if(blogListJsonStr != null && blogListJsonStr.length() > 0) {
					System.out.println("当前是使用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));
					
					//传到jsp页面
					request.setAttribute("blogList", blogList);
				}
			} 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);
			//清空缓存
			jedis.del("blogList");
			// 获取当前博客的id
			int maxId = this.blogDao.maxId();
			// 添加到lucene 索引库中
			addIndex(maxId + "", parameterMap);
			// 将这篇博客进行网页静态化
			addStaticPage(maxId + "", parameterMap);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "blogList";
	}

	/**
	 * 这是删除博客的方法
	 */
	public String del() {
		try {
			// 数据库中删除博客
			this.blogDao.del(bid);
			//清空缓存
			jedis.del("blogList");
			// 删除lucene中对应的文档
			IndexWriter indexWriter = getIndexWriter();
			indexWriter.deleteDocuments(new Term("id", bid));
			indexWriter.forceMergeDeletes(); // 强制删除
			indexWriter.commit();
			indexWriter.close();
			// 删除页面
			new File("D:\\code\\code_eclipse\\临时项目\\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());
			//清空缓存
			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("D:\\code\\code_eclipse\\临时项目\\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("D:\\code\\code_eclipse\\临时项目\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\" + id
						+ ".html"));
		// 7.输出
		template.process(map, out);
		// 8.关闭Writer对象
		out.close();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值