redis学习(案例)
Posted 食惯嘴第一才子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis学习(案例)相关的知识,希望对你有一定的参考价值。
效果如下
注意:必须要开启redis服务器端
数据库
CREATE DATABASE heima; -- 创建数据库 USE heima; -- 使用数据库 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包
jedis.properties
host=127.0.0.1 port=6379 maxTotal=50 maxIdle=10
js包
加入redis缓存
目录结构
html网页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>redis缓存+json</title> <script src="js/jquery-3.3.1.min.js"></script> <script> $(function () { //发送ajax请求,加载所有省份数据 $.get("provinceServlet",{},function (data) { //json[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"广州"},{"id":4,"name":"陕西"}] /* 1.获取select 2.遍历json数组 3.创建<option> 4.调用select的append追加option */ //1.获取select var province=$("#province"); //2.遍历json数组 $(data).each(function () { // 3.创建<option> var option="<option id=\'"+this.id+"\'>"+this.name+"</option>"; //4.调用select的append追加option province.append(option); }); }); }); </script> </head> <body> <select id="province"> <option>---请选择省份---</option> </select> </body> </html>
Servlet类
@WebServlet("/provinceServlet") public class ProvinceServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* 1.调用service查询 2.序列化(写)list为json 3.响应结果 */ // //1.调用service查询 // ProvinceService service=new ProvinceServiceImpl(); // List<Province> list = service.findAll(); // //2.序列化(写)list为json // ObjectMapper mapper=new ObjectMapper(); // String json = mapper.writeValueAsString(list); //1.调用service查询 ProvinceService service=new ProvinceServiceImpl(); String json = service.findAllJson(); //System.out.println("json"+json); //json[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"广州"},{"id":4,"name":"陕西"}] //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); } }
Javabean
public class Province { private int id; private String name; public Province() { } public Province(int id, String name) { this.id = id; this.name = 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; } }
dao
public interface ProvinceDao { public List<Province> findAll(); }
dao Impl
public class ProvinceDaoImpl implements ProvinceDao { private JdbcTemplate template=new JdbcTemplate(JDBCUtil.getDataSource()); @Override public List<Province> findAll() { String sql="select * from province"; List<Province> list = template.query(sql, new BeanPropertyRowMapper<Province>(Province.class)); return list; } }
service
public interface ProvinceService { public List<Province> findAll(); //redis缓存 public String findAllJson(); }
sevice Impl(核心)
public class ProvinceServiceImpl implements ProvinceService { private ProvinceDao provinceDao=new ProvinceDaoImpl(); @Override public List<Province> findAll() { return provinceDao.findAll(); } /* 使用redis缓存 */ @Override public String findAllJson() { //1.先从redis中查询数据 //1.1获取redis客户端连接 Jedis jedis = JedisUtil.getJedis(); String province_json = jedis.get("province"); //2判断province是否为空 if (province_json==null||province_json.length()==0){ System.out.println("redis没有数据 --- 查询数据库"); //2.1province为空,也就是redis没有数据 --- 查询数据库 List<Province> ps = provinceDao.findAll(); //2.2将ps 序列化为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); //3.归还连接 jedis.close(); }else { System.out.println("redis有数据 ---- 查询redis缓存"); //province不为空,也就是redis有数据 ---- 查询redis缓存 } return province_json; } }
工具类
JDBCUtil
public class JDBCUtil { private static DataSource ds; static { //读取配置文件 InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"); //创建Properties对象 Properties pro =new Properties(); try { //获取关联 pro.load(is); //2.初始化druid数据库连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } public static DataSource getDataSource(){ return ds; } public static Connection getConnection() throws SQLException { return ds.getConnection(); } //释放资源 public void close(Connection conn, PreparedStatement ps){ if (ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //释放资源 public void close(Connection conn, PreparedStatement ps, ResultSet rs){ close(conn,ps); if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
JedisUtil
public class JedisUtil { //工具类主要都是获取Jedis private static JedisPool jedisPool; static { //读取配置文件 InputStream is = JedisUtil.class.getClassLoader().getResourceAsStream("jedis.properties"); //创建Properties对象 Properties pro=new Properties(); //关联文件 try { pro.load(is); } catch (Exception e) { e.printStackTrace(); } JedisPoolConfig config=new JedisPoolConfig(); config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle"))); jedisPool=new JedisPool(pro.getProperty("host"),Integer.parseInt(pro.getProperty("port"))); } public static Jedis getJedis(){ return jedisPool.getResource(); } }
druid.properties配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/heima?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username=root password= # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000
jedis.properties配置文件
host=127.0.0.1 port=6379 maxTotal=50 maxIdle=10
以上是关于redis学习(案例)的主要内容,如果未能解决你的问题,请参考以下文章
使用java jedis封装Redis Stream操作案例