Redis(案例)省份 下拉列表

 

案例需求:


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

 

* 注意:

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

 

(为了方便演示用是IDEA+servle+maven+mysql+redis+Ajax+html,没有使用SSM进行整合,这节重点在redis,请谅解,原理都是一样的)

 

1.首先项目结构

2.maven依赖

<dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.1</version>
        </dependency>

    </dependencies>

3.domain实体类

/**
 * Created by Carl Wu on 2020/3/30 1:10
 */
public class Province {

    private int id;
    private String name;

    public Province() {
    }

    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 + '\'' +
                '}';
    }
}

4.servlet代码

/**
 * Created by Carl Wu on 2020/3/30 1:08
 */
@WebServlet("/provinceServlet")
public class ProvinceServlet  extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * Province{id=1, name='北京'}
         * Province{id=2, name='上海'}
         * Province{id=3, name='广州'}
         * Province{id=4, name='陕西'}
         */
        //调用service查询
        /*ProvinceService service = new ProvinceServiceImpl();
        List<Province> provinces = service.findAll();
        provinces.forEach(province -> {
            System.out.println(province);
        });
        //序列化list为json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(provinces);
        //响应结果
        System.out.println(json);*/


        ProvinceService service = new ProvinceServiceImpl();
        String json = service.findAllJson();

        System.out.println(json);

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }

}

5.utils工具类

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

/**
 * Created by Carl Wu on 2020/3/30 0:47
 */

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

    private static JedisPool jedisPool;

    static{
        //读取配置文件
        //  JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties")
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        System.out.println(is);
        //创建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();
    }
}

6.service接口代码

/**
 * Created by Carl Wu on 2020/3/30 1:10
 */
public interface ProvinceService {

    /**
     * 查询全部
     * @return
     */
    List<Province> findAll();

    /**
     * 查询全部省份信息,返回json数据
     * @return
     */
    String findAllJson();

}

7. service接口实现类代码

/**
 * Created by Carl Wu on 2020/3/30 1:10
 */
public class ProvinceServiceImpl implements ProvinceService {

    private ProvinceDao provinceDao = new ProvinceDaoImpl();

    /**

     * 查询全部的省份
     * @return
     */
    @Override
    public List<Province> findAll() {
        return provinceDao.findAll();
    }

    /**
     *  * 使用缓存
     * 查询全部省份信息,返回json数据
     * @return
     */
    @Override
    public String findAllJson() {

        //先从redis中查询数据
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");
        if (province_json == null || province_json.length() == 0){
            System.out.println("redis中没有数据,查询数据库");
            List<Province> provinces = provinceDao.findAll();
            ObjectMapper mapper = new ObjectMapper();
            try {
                province_json = mapper.writeValueAsString(provinces);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //将数据存入到redis中
            jedis.set("province",province_json);
            jedis.close();
        }else {
            System.out.println("redis中有数据,查询缓存.....");
        }
        return province_json;
    }
}

8.dao接口代码

/**
 * Created by Carl Wu on 2020/3/30 1:11
 */
public interface ProvinceDao {

    /**
     * 查询全部的省份
     * @return
     */
    List<Province> findAll();

}

9.dao接口实现类代码

/**
 * Created by Carl Wu on 2020/3/30 1:11
 */
public class ProvinceDaoImpl implements ProvinceDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 查询全部的省份信息
     * @return
     */
    @Override
    public List<Province> findAll() {
        String sql = "select * from province";
        List<Province> list = template.query(sql, new BeanPropertyRowMapper<>(Province.class));
        return list;
    }
}

10.index.html代码

<!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":"陕西"}]

               var province = $("#province");

               $(data).each(function () {
                   //拼接字符串
                   var option = "<option name '"+this+"'>" +this.name + "</option>";

                   province.append(option);
               })
           });
        });
    </script>
</head>
<body>

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

</body>
</html>

11.druid.properties资源文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///redis
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

12.jedis.properties资源文件

host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10

13.执行结果界面

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值