数据库
首页 > 数据库> > Redis案例 February 3,2020

Redis案例 February 3,2020

作者:互联网

## 案例:
案例需求:
  1. 提供index.html页面,页面中有一个省份 下拉列表
  2. 当 页面加载完成后 发送ajax请求,加载所有省份

  * 注意:使用redis缓存一些不经常发生变化的数据。
    * 数据库的数据一旦发生改变,则需要更新缓存。
    * 数据库的表执行 增删改的相关操作,需要将redis缓存数据情况,再次存入
    * 在service对应的增删改方法中,将redis数据删除。

 

分析:

 

 

 

代码结构:

 

 

 

代码:

dao

 

package dao;

import domain.Province;

import java.util.List;

public interface ProvinceDao {
    //查询所有
    public List<Province> findAll();
}

 

 

package dao.impl;


import dao.ProvinceDao;
import domain.Province;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

import java.util.List;

public class ProvinceDaoImpl implements ProvinceDao {
    //1.声明成员变量 JdbcTemplate
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());


    @Override
    public List<Province> findAll() {
        //1.定义sql
        String sql = "select * from province";
        //2.执行sql
        List<Province> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Province>(Province.class));
        return list;
    }
}

 

domain

 

package domain;

public class Province {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Province{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

 

service

 

package service;

import domain.Province;

import java.util.List;

public interface ProvinceService {
    //查询所有
    public List<Province> findAll();

    public String finAllJson();
}

 

 

package service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.ProvinceDao;
import dao.impl.ProvinceDaoImpl;
import domain.Province;
import redis.clients.jedis.Jedis;
import service.ProvinceService;
import util.JedisPoolUtils;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    private ProvinceDao provinceDao = new ProvinceDaoImpl();
    @Override
    public List<Province> findAll() {
        return provinceDao.findAll();
    }

    /**
     * 使用redis缓存
     * @return
     */
    @Override
    public String finAllJson() {
        //1.先从redis中查询数据
        //1.1获取redis客户端连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String redis_json = jedis.get("province");
        //2判断 redis_json 数据是否为null
        if(redis_json ==null || redis_json.length() == 0){
            //redis中没有缓存
            System.out.println("redis中不存在缓存,从数据库查询");
            //2.1从数据库查询
            List<Province> list = provinceDao.findAll();
            //2.2将list序列化为json
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                redis_json = objectMapper.writeValueAsString(list);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //2.3 将json数据存入redis
            jedis.set("province",redis_json);
            //归还连接
            jedis.close();
        }else {
            System.out.println("redis存在缓存");

        }
        return redis_json;
    }
}

 

util

 

package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类 使用Durid连接池
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2.初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

 

 

package util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


/**
 JedisPool工具类
 加载配置文件,配置连接池的参数
 提供获取连接的方法

 */
public class JedisPoolUtils {

    private static JedisPool jedisPool;

    static{
        //读取配置文件
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        //创建Properties对象
        Properties pro = new Properties();
        //关联文件
        try {
            pro.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取数据,设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));

        //初始化JedisPool
        jedisPool = new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));



    }


    /**
     * 获取连接方法
     */
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

 

 

 

 

web

 

package web.servlet;


import service.ProvinceService;
import service.impl.ProvinceServiceImpl;

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;


@WebServlet("/findProvinceServlet")
public class FindProvinceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//         //1.调用service查询
//        ProvinceService provinceService = new ProvinceServiceImpl();
//        List<Province> list = provinceService.findAll();
//        //2.序列化list为json
//        ObjectMapper objectMapper = new ObjectMapper();
//        String json = objectMapper.writeValueAsString(list);

        //1.调用service查询
       ProvinceService provinceService = new ProvinceServiceImpl();
        String json = provinceService.finAllJson();
        System.out.println(json);
        //3.响应结果
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
           //发送ajax请求,获取所有省份信息
            $.get("findProvinceServlet",{},function (data) {
                //[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"广州"},{"id":4,"name":"陕西"}]
                //1.获取select的id
                var province = $("#province");
                //2.遍历json数组
                //  for (var i = 0; i < data.length; i++) {
                //      var opption = "<option name='"+data[i].id+"'>"+data[i].name+"</option>"
                //      province.append(opption);
                //  }

                $(data).each(function () {
                    //3.创建option标签
                    var opption = "<option name='"+this.id+"'>"+this.name+"</option>"
                    //4.调用select的append追加option
                    province.append(opption);
                });


           });

        });

    </script>
</head>
<body>
    <select id="province">
        <option>--请选择省份-- </option>

    </select>
</body>
</html>

 

标签:February,java,name,redis,Redis,json,2020,import,public
来源: https://www.cnblogs.com/yyanghang/p/12255449.html