Redis实例1:获取下拉框数据

hwm 2020-06-17


1.介绍

目的:使用redis缓存数据。第一次需要从数据库获得数据,第二次直接从redis中获取。通常用在缓存不常变化的数据。

需求:

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

流程:

Redis实例1:获取下拉框数据

 2.代码展示

2.1.index.html

Redis实例1:获取下拉框数据

<!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("provinceServlet",{},function (data) {
                //[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"广州"},{"id":4,"name":"陕西"}]

                //1.获取select
                var province = $("#province");
                //2.遍历json数组
                //$(data).each(function () {
                $.each(data, function () {
                    //3.创建<option>
                    var option = "<option value=‘"+this.id+"‘>"+this.name+"</option>";

                    //4.调用select的append追加option
                    province.append(option);
                });


            });
            
        });
        
        
    </script>
    
</head>
<body>

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

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

2.2.创建数据库

CREATE DATABASE RP; -- 创建数据库
USE RP; 			   -- 使用数据库
CREATE TABLE province(   -- 创建表
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20) NOT NULL
	
);
-- 插入数据
INSERT INTO province VALUES(NULL,‘北京‘);
INSERT INTO province VALUES(NULL,‘上海‘);
INSERT INTO province VALUES(NULL,‘广州‘);
INSERT INTO province VALUES(NULL,‘陕西‘);

2.3.ProvinceDaoImpl

public class ProvinceDaoImpl implements ProvinceDao {

    //1.声明成员变量 jdbctemplement
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

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

2.4.ProvinceServiceImpl

public class ProvinceServiceImpl implements ProvinceService {

    //声明dao
    private ProvinceDao dao = new ProvinceDaoImpl();
    /**
        使用redis缓存
     */

    @Override
    public String findAllJson() {
        //1.先从redis中查询数据
        //1.1获取redis客户端连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");

        //2判断 province_json 数据是否为null
        if(province_json == null || province_json.length() == 0){
            //redis中没有数据
            System.out.println("redis中没数据,查询数据库...");
            //2.1从数据中查询
            List<Province> ps = dao.findAll();
            //2.2将list序列化为json
            ObjectMapper mapper = new ObjectMapper();
            try {
                province_json = mapper.writeValueAsString(ps);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            //2.3 将json数据存入redis
            jedis.set("province",province_json);
            //归还连接
            jedis.close();

        }else{
            System.out.println("redis中有数据,查询缓存...");
        }
        return province_json;
    }
}

2.5.web.servelt

@WebServlet("/provinceServlet")
public class ProvinceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.调用service查询
        ProvinceService service = new ProvinceServiceImpl();
        String json = service.findAllJson();


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

相关推荐