首页 > 其他分享 > Jedis案例

Jedis案例

时间:2022-08-23 10:34:53浏览次数:48  
标签:java name com 案例 Jedis import ailyt public

案例:

  • 案例需求:
    • 提供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;
    }

标签:java,name,com,案例,Jedis,import,ailyt,public
From: https://www.cnblogs.com/ailhy/p/16615265.html

相关文章

  • JQuery抽奖案例实现
    JQuery抽奖案例实现分析:给开始按钮绑定单机事件定义循环定时器切换小相框的src属性定义一个数组,存放图片资源......
  • JQuery案例 1_广告显示与隐藏
    JQuery案例1_广告显示与隐藏需求:当页面加载完,3秒后,自动显示广告广告显示5秒后,自动消失分析:使用定时器来完成,setTimeout(执行一次定时器)分析发现JQue......
  • SQL案例
    1.selecte.employee_nameASMANAGER,ROW_NUMBER()over(PARTITIONbye.dateorderbye.salaryDESC)ASRNFROM((selectDISTINCTb.manager_id,a.employee_namefro......
  • 项目案例-运用西门子PLC通过Modbus RTU采集YGWE通讯数据
    本案例控制的是YGWE冷却系统。系统主PLC选用西门子CPU,通过Modbus转Profinet网关采集YGWE通讯数据。 1、首先创建新项目文件;  2、导入GSD文件,将小疆智控MODBUS转PR......
  • 案例
    案例需求:提供index.html页面页面中有一个省份下拉列表当页面加载完成后发送ajax请求加载所有省份java代码实现配置文件数据库配置文件:druid.propertiesdrive......
  • jedis连接池
    jedis连接池使用:创建JedisPool连接池对象调用方法getResource()方法获取Jedis连接java代码@Testpublicvoidtest07(){//创建一个配置对象......
  • Jedis连接池和Jedis连接池工具类
    Jedis连接池对象:@TestpublicvoidMyTest06(){//创建配置对象JedisPoolConfigjedisPoolConfig=newJedisPoolConfig();jedisPoo......
  • Jedis快速入门和Jedis操作string
    Java客户端JedisJedis:一款java操作redis数据库的工具使用步骤:下载jedis的jar包使用<!--https://mvnrepository.com/artifact/redis.clients/jedis-->......
  • Jedis操作hash和Jedis操作list
    Jedis操作hash/***hash*/@Testpublicvoidtest3(){//1.获取连接Jedisjedis=newJedis();//如果使用空参构造,默认值"localhost",6379端口//存......
  • Jedis查询数据库案例
    Jedis查询数据库案例分析:环境搭建:sql:CREATETABLEprovince(--创建表idINTPRIMARYKEYAUTO_INCREMENT,NAMEVARCHAR(20)NOTNULL);--插入......