Jedis案例


案例:

  • 案例需求:
    • 提供index.html页面,页面中有一个省份 下拉列表
    • 当页面加载完成后 发送ajax请求,加载所有省份
      代码实现:
ProvinceDao
package com.ailyt.dao;

import com.ailyt.pojo.Province;

import java.util.List;

public interface ProvinceDao {
    public List<Province> findAll();
}

ProvinceDaoImpl
package com.ailyt.dao.impl;

import com.ailyt.dao.ProvinceDao;
import com.ailyt.pojo.Province;
import com.ailyt.utils.JDBCUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.stat.JdbcDataSourceStat;
import lombok.SneakyThrows;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

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

public class ProvinceDaoImpl implements ProvinceDao {

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    @SneakyThrows
    @Override
    public List<Province> findAll() {
        String sql = "select * from province";
        List<Province> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Province>(Province.class));
        return query;
    }
}

Province
package com.ailyt.pojo;

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

    @Override
    public String toString() {
        return "Province{" +
                "id=" + id +
                ", name='" + 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;
    }

    public Province() {
    }

    public Province(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

ProvinceService
package com.ailyt.service;

import com.ailyt.pojo.Province;

import java.util.List;

public interface ProvinceService {
    public List<Province> findAll();

}

ProvinceServiceImpl
package com.ailyt.service.impl;

import com.ailyt.dao.impl.ProvinceDaoImpl;
import com.ailyt.pojo.Province;
import com.ailyt.service.ProvinceService;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    private ProvinceDaoImpl provinceDao = new ProvinceDaoImpl();

    @Override
    public List<Province> findAll() {
        return provinceDao.findAll();
    }
}

ProvinceServlet
package com.ailyt.servlet;

import com.ailyt.pojo.Province;
import com.ailyt.service.impl.ProvinceServiceImpl;
import com.ailyt.utils.JedisPoolUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "provinceServlet", value = "/provinceServlet")
public class ProvinceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProvinceServiceImpl servlet = new ProvinceServiceImpl();
        List<Province> list = servlet.findAll();
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(list);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);


    }
}

JDBCUtils
package com.ailyt.utils;

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

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="js/jquery-3.6.0.min.js"></script>
    <script>
        $(function () {
            //发送ajax请求,加载所有省份数据
            $.get("provinceServlet",{}, function (data) {
                var province = $("#province");
                $(data).each(function () {
                    var option = "<option name='"+this.id+"'>"+this.name+"</option>";
                    province.append(option);
                });

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

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

案例redis缓存优化

 @SneakyThrows
    @Override
    public String findAllJson() {

        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");

        final boolean condition = province_json == null || province_json.length() ==0;

        if (condition) {
            System.out.println("redis中没有数据从数据库中查询");
            List<Province> ps = provinceDao.findAll();
            ObjectMapper mapper = new ObjectMapper();
            province_json = mapper.writeValueAsString(ps);
            jedis.set("province", province_json);

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

        jedis.close();

        return province_json;
    }

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/281815.html

(0)
上一篇 2022年8月23日
下一篇 2022年8月23日

相关推荐

发表回复

登录后才能评论