在Java中操作redis

Java访问redis
2.1 添加依赖

redis.clients
jedis
2.9.0

2.2 Java连接redis
Jedis jedis = new Jedis(ip, port);
jedis.auth(“123456”);//权限认证
jedis.ping();
jedis.select(0);//切换数据库

2.3 Java操作redis
string(字符串)
hash(哈希)
list(列表)
set(集合)
zset(sorted set:有序集合)
zadd/zrevrange
注1:不需要记得API的方法,只需要查redis命令

基础操作

package com.zking;

import redis.clients.jedis.Jedis;

/**
 * @author润红的爸爸
 * @site www.xiaomage.com
 * @company 潇洒公司
 * @create 2019-09-18 10:55
 */
public class demo1 {
//    连接redis
    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.252.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"));

//        操作列表list
        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"));
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2.案例
当我们查数据时,可以利用redis。第一次查询查询数据库,然后将数据放入redis中,之后的数据就直接从redis中获取
home.jsp

<%--
  Created by IntelliJ IDEA.
  User: lx
  Date: 2019/9/18
  Time: 11:09
  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>

demoServlet

package com.zking;

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-18 11:09
 */
@WebServlet("/getData")
public class demoSevlet 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.252.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);
        }else{
            req.setAttribute("msg","我是从数据库中拿的");
            String uname = "wanwu";
            String upass = "123456";
            jedis.hset("currentUser","uname","wanwu");
            jedis.hset("currentUser","upass","123456");
            currentUser = jedis.hgetAll("currentUser");
            req.setAttribute("currentUser",currentUser);
        }
        req.getRequestDispatcher("/home.jsp").forward(req,resp);
    }
}


在这里插入图片描述
在这里插入图片描述
1、首页第一次是读取数据库,后面读取缓存(在没有增删改的情况)

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";
	}

2、增删改的时候,要顺带更新缓存,下一次再次访问首页要保证redis中数据跟mysql数据是一致

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) {
			System.out.println("增加成功");
//			更新缓存
			jedis.del("list");
			List<Map<String, Object>> list = blogDao.list(null, null);
			jedis.set("list", JSON.toJSONString(list));
//			新增索引
			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));
				System.out.println("添加索引成功");
//				新增静态页面
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "blogList";
		}
		else {
			System.out.println("增加失败");
			return "blogList";
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值