本文与上一节关联紧密,先看完上一节再过来
现在我们用redis(非关系型数据库)外加mysql来实现,一张图看懂操作
redis使用Jedis来连接数据库,mysql使用JDBC连接数据库
总体层次
新增坐标
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
service层
public interface ProvinceCityService {
/**
* 获取省数据
* @return
*/
public List<Province> getProvince();
/**
* 获取省数据
* @return
*/
public List<City> getCity(String codePid);//省份的id
/**
* 获取省
*/
public String getProvinceJson();
/**
* 获取市
* pId 省id
*/
public String getCityJson(String pId);
}
这里city后面加上了Pid主要是将城市和它的市绑定在一起,不然它不会联动
public class ProvinceCityServiceImpl implements ProvinceCityService{
ProvinceCityDao provinceCityDao = new ProvinceDaoImpl();
@Override
public List<Province> getProvince() {
return provinceCityDao.getProvince();
}
@Override
public List<City> getCity(String codePid) {
return provinceCityDao.getCity(codePid);
}
@Override
public String getProvinceJson() {
//建立连接
Jedis jedis = JedisPoolUtils.getJedis();
//获取缓存中的参数
String provinceJson = jedis.get("province");
//判断是否为空
if (provinceJson==null || provinceJson.length()==0) {
//说明第一次查,那么要去mysql
List<Province> list = provinceCityDao.getProvince();
//将集合转换为json
ObjectMapper mapper = new ObjectMapper();
try {
provinceJson = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//存入redis
jedis.set("province",provinceJson);
//关闭
jedis.close();
}else{
System.out.println("redis缓存中存在");
}
return provinceJson;
}
@Override
public String getCityJson(String pId) {
//建立连接
Jedis jedis = JedisPoolUtils.getJedis();
//获取缓存中的参数
String cityJson = jedis.get("city"+pId);
//判断是否为空
if (cityJson==null || cityJson.length()==0) {
//说明第一次查,那么要去mysql
List<City> list = provinceCityDao.getCity(pId);
//将集合转换为json
ObjectMapper mapper = new ObjectMapper();
try {
cityJson = mapper.writeValueAsString(list);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//存入redis
jedis.set("city"+pId,cityJson);
//关闭
jedis.close();
}else{
System.out.println("redis缓存中存在");
}
return cityJson;
}
}
CityAction
@WebServlet("/getCity")
public class CityAction extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求编码格式 Request
req.setCharacterEncoding("UTF-8");
//处理 Response 响映json编码格式'
resp.setContentType("application/json;charset=UTF-8");
//获取参数
String codePid = req.getParameter("id");
//创建控制层
ProvinceCityService provinceCityService = new ProvinceCityServiceImpl();
String cityJson = provinceCityService.getCityJson(codePid);
resp.getWriter().println(cityJson);
}
}
ProvinceAction
@WebServlet("/getProvince")
public class ProvinceAction extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求编码格式 Request
req.setCharacterEncoding("UTF-8");
//处理 Response 响映json编码格式
resp.setContentType("application/json;charset=UTF-8");
ProvinceCityService provinceCityService = new ProvinceCityServiceImpl();
String provinceJson = provinceCityService.getProvinceJson();
resp.getWriter().println(provinceJson);
}
}
redis工具类
public class JedisPoolUtils {
private static JedisPool jedisPool;
//静态代码块
static {
//读取配置文件
InputStream inputStream = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties
Properties pro = new Properties();
try {
pro.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
//创建配置类
JedisPoolConfig config = new JedisPoolConfig();
//最大连接数
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
//最在空闲连接
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
//获取配置文件
String host = pro.getProperty("host");
Integer port = Integer.parseInt(pro.getProperty("port"));
jedisPool = new JedisPool(config,host,port);
}
public static Jedis getJedis(){
Jedis jedis = jedisPool.getResource();
return jedis;
}
}
配置文件
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<script src="js/jquery-3.3.1.js"></script>
<script>
$(function () {
$.get("${pageContext.request.contextPath}/getProvince", function(data){
var province = $("#province")
document.getElementById('province').options.length = 0
province.append('<option value="-1">--请选择省份--</option>')
$(data).each(function () {
var option = "<option value='"+this.codePid+"'>"+this.name+"</option>"
province.append(option)
})
});
})
function getCity(codePid) {
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/getCity",
data: "id="+codePid,
data_type: "json",
success: function(data){
var city = $("#city")
document.getElementById('city').options.length = 0
city.append("<option>--请选择市--</option>")
$(data).each(function () {
var option = "<option value='"+this.codePid+"'>"+this.name+"</option>"
city.append(option)
})
}
});
}
</script>
</head>
<body>
<select id="province" onchange="getCity(this.value)">
<option>--请选择省份--</option>
</select>
<select id="city">
<option>--请选择市--</option>
</select>
</body>
</html>