java操作Redis

时间:2019-09-19
本文章向大家介绍java操作Redis,主要包括java操作Redis使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Java访问redis

Java操作redis
string(字符串)
hash(哈希)
list(列表)
set(集合) 

zset(sorted set:有序集合)

package com.cjh;

import redis.clients.jedis.Jedis;

/**
 * @author
 * @site
 * @company
 * @create 2019-09-18 11:21
 *
 * 讲的是java代码操作redis
 * 链接redis
 * 操作字符串
 * 操作哈希
 * 操作列表list
 *
 */
public class Dome1 {

    public static void main(String[] args) {
        Jedis jedis = new Jedis("192.168.198.129" ,6379);
        jedis.auth("123456");
        System.out.println(jedis.ping());

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




//        //操作哈希
//        jedis.hset("user","uname","蔡徐坤");
//
//        jedis.hset("user","sex","女");
//        //取一个对象
//        System.out.println(jedis.hgetAll("user"));
//        //取一个对象里面的一个值
//        System.out.println(jedis.hget("user", "uname"));


        //操作列表

        jedis.lpush("hobby","","","rap");
        System.out.println(jedis.lpop("hobby"));
        System.out.println(jedis.lpop("hobby"));
        System.out.println(jedis.rpop("hobby"));
    }

}
package com.cjh;

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
 * @company
 * @create 2019-09-18 11:46
 */
@WebServlet("/getData")
public class DomeServlet 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.198.129" ,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 = "蔡徐坤";
          String upwd = "123456";
          //把数据中对应对象存储到缓存中
          jedis.hset("currentUser","uanem","蔡徐坤");
          jedis.hset("currentUser","upwd","123456");
          //能获取到值是上面已经把数据存储到缓存中
          currentUser= jedis.hgetAll("currentUser");
          req.setAttribute("currentUser",currentUser);
      }
      req.getRequestDispatcher("/home.jsp").forward(req,resp);
    }
}

项目运用Redis

优化luncec和网页静态化代码:

pom依赖:

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

只需要修改请求层里面的代码

package com.javaxl.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 com.alibaba.fastjson.JSON;
import com.javaxl.blog.dao.BlogDao;
import com.javaxl.blog.util.JsonUtils;

import com.javaxl.blog.util.PropertiesUtil;
import com.javaxl.blog.util.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import redis.clients.jedis.Jedis;
/**
 * 专门将网页静态化的类,这里不涉及到lucene
 * 
 * @author Administrator
 *
 */
public class FreemarkerBlogAction {
    private String title;
    private String bid;
    private BlogDao blogDao = new BlogDao();

    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;
    }
    
    private static String add="192.168.198.129";

    
    /**
     * 连接redis
     * @return
     */
    public static Jedis Jedis() {
        Jedis jedis = new Jedis(add, 6379);
        jedis.auth("123456");
        return jedis;
    }
    /**
     * 查询博客
     * @return
     */
    public String list() {

        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            Jedis jedis = Jedis();
            
            if (StringUtils.isBlank(title)) {
                if(jedis.get("blogList")!=null && jedis.get("blogList").length()>0) {
                    System.out.println("从缓存里面拿数据");
                    request.setAttribute("blogList", JSON.parse(jedis.get("blogList")));
                }
                else {    
                    System.out.println("从数据里拿数据");
                    //从数据库里面拿数据
                    List<Map<String, Object>> list = this.blogDao.freemarker_list(title, null);
                    //放人Redis缓存
                    jedis.set("blogList", JSON.toJSONString(list));
                    //传到jsp页面
                    request.setAttribute("blogList", list);
                }
                
            } 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) {
            // TODO: handle exception
        }

        return "blogList";
    }

    public String show() {
        HttpServletRequest request = ServletActionContext.getRequest();
        try {
            Map<String, Object> blog = this.blogDao.freemarker_show(bid).get(0);
            request.setAttribute("blog", blog);
        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "blogDetail";
    }

    /**
     * 刷新全局索引
     * 
     * @return
     */
    public String Starter() {
        IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
        Directory d;
        IndexWriter indexWriter = null;
        try {
            // 将原先的索引文件刪除
            del(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 (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        finally {
            try {
                if (indexWriter != null) {
                    indexWriter.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return "blogList";
    }

    /**
     * 将原先的索引文件刪除
     * 
     * @param file
     */
    private void del(File file) {
        // TODO Auto-generated method stub
        if (file.isDirectory()) {
            String[] children = file.list();// 获取文件夹下所有子文件夹
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                del(new File(file, children[i]));
            }
        }
        // 目录空了,进行删除
        file.delete();
    }

    /**
     * 添加博客
     * 
     * @return
     */

    public String add() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map parameterMap = request.getParameterMap();
        try {
            
            this.blogDao.add(parameterMap);
            //删除缓存
            Jedis jedis = Jedis();
            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";
    }
/**
 * 删除博客
 * @return
 */
    public String del() {
        try {
            // 数据库中删除博客
            this.blogDao.del(bid);
            //删除缓存
            Jedis jedis = Jedis();
            jedis.del("blogList");
            // 删除lucene中对应的文档
            IndexWriter indexWriter = getIndexWriter();
            indexWriter.deleteDocuments(new Term("id", bid));
            indexWriter.forceMergeDeletes();
            indexWriter.commit();
            indexWriter.close();
            // 删除页面
            new File("E:\\y2\\17、freemarker\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\" + bid
                    + ".html").delete();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return "blogList";
    }
/**
 * 修改前
 * @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 "edit";
    }

    /**
     * 修改
     * @return
     */
    public String edit() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map parameterMap = request.getParameterMap();
        try {
            // 修改数据库中的值
            this.blogDao.edit(request.getParameterMap());
            //删除缓存
            Jedis jedis = Jedis();
            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";
    }
    
    
    /**
     * 将这篇博客进行网页静态化
     * 
     * @param string
     * @param parameterMap
     * @throws IOException
     */
    private void addStaticPage(String id, Map parameterMap) throws IOException {
        // TODO Auto-generated method stub
        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();

    }

    private IndexWriter getIndexWriter() throws IOException {
        // TODO Auto-generated method stub
        IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
        Directory d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
        return new IndexWriter(d, conf);

    }

    /**
     * 添加到lucene 索引库中
     * 
     * @param string
     * @param parameterMap
     * @throws IOException
     * @throws TemplateException
     */
    private void addIndex(String id, Map parameterMap) throws IOException, TemplateException {
        // TODO Auto-generated method stub
        // 1.创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 2.设置模板所在的目录
        configuration.setDirectoryForTemplateLoading(
                new File("E:\\y2\\17、freemarker\\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(
                "E:\\y2\\17、freemarker\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\" + id + ".html"));
        // 7.输出
        template.process(map, out);
        // 8.关闭Writer对象
        out.close();
    }

}

效果:

很明显从缓存里面拿数据要比从数据库里面拿数据要快

原文地址:https://www.cnblogs.com/chenjiahao9527/p/11550667.html