- Java后端 学习路线 笔记汇总表【黑马程序员】
- Redis-学习笔记01【Redis环境搭建】
- Redis-学习笔记02【Redis命令操作】
- Redis-学习笔记03【Redis持久化】
- Redis-学习笔记04【Jedis代码操作】
- Redis-学习笔记05【Jedis连接池】
- Redis-学习笔记06【Redis案例】
目录
第6节 Redis案例
案例_分析&环境搭建
day23.sql
druid.properties
案例_实现_查询数据库
案例_实现_redis缓存优化
package cn.itcast.dao;
ProvinceDaoImpl.java
ProvinceDao.java
package cn.itcast.domain;
Province.java
package cn.itcast.jedis;
JedisPoolUtils.java
package cn.itcast.service;
ProvinceServiceImpl.java
ProvinceService.java
package cn.itcast.util;
JDBCUtils.java
package cn.itcast.web;
ProvinceServlet.java
web
index.html
案例
案例需求:
1. 提供index.html页面,页面中有一个省份(下拉列表)。
2. 当页面加载完成后,发送ajax请求,加载所有省份。
案例
CREATE DATABASE day23; -- 创建数据库
USE day23; -- 使用数据库
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,'陕西');
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day23
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
* 注意:使用redis缓存一些不经常发生变化的数据。
* 数据库的数据一旦发生改变,则需要更新缓存。
* 数据库的表执行“增删改”的相关操作,需要将redis缓存数据清空,再次存入。
* 在service对应的增删改方法中,将redis数据删除。
package cn.itcast.dao.impl;
import cn.itcast.dao.ProvinceDao;
import cn.itcast.domain.Province;
import cn.itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class ProvinceDaoImpl implements ProvinceDao {
//1.声明成员变量 jdbctemplement
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List findAll() {
//1.定义sql
String sql = "select * from province ";
//2.执行sql
List list = template.query(sql, new BeanPropertyRowMapper(Province.class));
return list;
}
}
package cn.itcast.dao;
import cn.itcast.domain.Province;
import java.util.List;
public interface ProvinceDao {
public List findAll();
}
package cn.itcast.domain;
public class Province {
private int id;
private String 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;
}
}
package cn.itcast.jedis.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();
//pro.getProperty("maxTotal"):获取的值是字符串,配置要求的是int值
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();//获取连接
}
}
package cn.itcast.service.impl;
import cn.itcast.dao.ProvinceDao;
import cn.itcast.dao.impl.ProvinceDaoImpl;
import cn.itcast.domain.Province;
import cn.itcast.jedis.util.JedisPoolUtils;
import cn.itcast.service.ProvinceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import java.util.List;
public class ProvinceServiceImpl implements ProvinceService {
//声明dao
private ProvinceDao dao = new ProvinceDaoImpl();
@Override
public List findAll() {
return dao.findAll();
}
/**
* 使用redis缓存
*/
@Override
public String findAllJson() {
//1.先从redis中查询数据
//1.1获取redis客户端连接
Jedis jedis = JedisPoolUtils.getJedis();
String province_json = jedis.get("province");
//2判断 province_json 数据是否为null
if (province_json == null || province_json.length() == 0) {
//redis中没有数据
System.out.println("redis中没数据,查询数据库...");
//2.1从数据中查询
List ps = dao.findAll();
//2.2将list序列化为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);
//归还连接
jedis.close();
} else {
System.out.println("redis中有数据,查询缓存...");
}
return province_json;
}
}
package cn.itcast.service;
import cn.itcast.domain.Province;
import java.util.List;
public interface ProvinceService {
public List findAll();
public String findAllJson();
}
package cn.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();
}
}
package cn.itcast.web.servlet;
import cn.itcast.service.ProvinceService;
import cn.itcast.service.impl.ProvinceServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/provinceServlet")
public class ProvinceServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* //1.调用service查询
ProvinceService service = new ProvinceServiceImpl();
List 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);
//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);
}
}
Title
加油~~~