Jedis查询数据库案例
分析:
环境搭建:
sql:
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,'陕西');
需要导入的jar包:
配置文件:
druid.properties:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql:///day23 username=root password=root initialSize=5 maxActive=10 maxWait=3000
jedis.properties:
#host=127.0.0.1 #host=localhost localhost=127.0.0.1 port=6379 maxTotal=50 maxIdle=10
需要创建的包:
注意:使用redis缓存一些不经常发生变化的数据。
数据库的数据一旦发生改变,则需要更新缓存。
数据库的表执行 增删改的相关操作,需要将redis缓存数据情况,再次存入
在service对应的增删改方法中,将redis数据删除
Province: 实体类
JDBCUtils:工具类
package cn.peng.itcast.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(); } }
JedisPoolUtils:工具类
package cn.peng.itcast.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("localhost"),Integer.parseInt(pro.getProperty("port"))); } /** * 获取连接方法 */ public static Jedis getJedis(){ return jedisPool.getResource(); } }
ProvinceDao:
public interface ProvinceDao { public List<Province> findAll(); }
ProvinceDaoImpl
public class ProvinceDaoImpl implements ProvinceDao { //声明成员变量 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public List<Province> findAll() { //定义sql String sql = "select * from province "; //执行sql List<Province> list = template.query(sql, new BeanPropertyRowMapper<Province>(Province.class)); return list; } }
ProvinceService
public interface ProvinceService { public List<Province> findAll(); public String findAllJson(); }
ProvinceServiceImpl
public class ProvinceServiceImpl implements ProvinceService { private ProvinceDaoImpl dao = new ProvinceDaoImpl(); @Override public List<Province> findAll() { return dao.findAll(); } /** * 使用redis缓存 * @return */ @Override public String findAllJson() { //先从redis中查询数据 //获取redis客户端连接 Jedis jedis = JedisPoolUtils.getJedis(); String province_json = jedis.get("province"); //判断province_json数据是否为null if (province_json==null|| province_json.length()==0){ System.out.println("没有数据查询数据库"); //redis中没有数据,从数据库中查询 List<Province> ps = dao.findAll(); //将list序列化为json ObjectMapper mapper = new ObjectMapper(); try { province_json = mapper.writeValueAsString(ps); } catch (JsonProcessingException e) { e.printStackTrace(); } //将json数据存入redis中 jedis.set("province",province_json); //归还连接 jedis.close(); }else { System.out.println("有数据查询缓存"); } return province_json; } }
ProvinceServlet
@WebServlet("/provinceServlet") public class ProvinceServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //调用service查询 ProvinceServiceImpl service = new ProvinceServiceImpl(); String json = service.findAllJson(); //System.out.println(json); //响应结果 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); } }
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) { //获取select var province = $("#province"); //变量数组 $(data).each(function () { //创建<option> var option = "<option name='"+this.id+"'>"+this.name+"</option>" //调用select的append追加option province.append(option); }); }); }); </script> </head> <body> <select id="province"> <option>--请选择省份--</option> </select> </body> </html>
多次访问此页面
第一次查询
降低查询数据库的访问率
后面的查询:
搜索
复制
标签:province,redis,new,案例,json,Jedis,查询数据库,import,public From: https://www.cnblogs.com/pengtianyang/p/16612066.html