目录
一、页面缓存、URL缓存
1.1 改造商品详情页面
不进行商品页面静态化处理,单做缓存处理。思路就是把整个html页面以字符串的形式放入redis缓存当中,然后为其设置一个过期时间,大约是60秒比较合适。当用户下次访问的时候就会直接从缓存中读取出html页面,然后将其渲染即可。
代码
修改leyou-goods-web中的GoodsController
@GetMapping(value = "{id}.html",produces = "text/html")
@ResponseBody
public String toItemPage(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id")String id){
Long idN = Long.parseLong(id);
//加载数据
Map<String, Object> modelMap = this.goodsService.loadModel(idN);
//把数据放入模型中
model.addAllAttributes(modelMap);
BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(KEY_PREFIX+id);
String html = (String) hashOperations.get(id);
/**
* 先取缓存
*/
if (StringUtils.isNotEmpty(html)){
//不空,则返回
return html;
}
//手动渲染模板
WebContext context = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
html = thymeleafViewResolver.getTemplateEngine().process("item",context);
if (StringUtils.isNotEmpty(html)){
//不空,放入缓存
//设置有效期60秒
hashOperations.put(id,html);
hashOperations.expire(60, TimeUnit.SECONDS);
}
return html;
}
这里面需要注意的是Thymeleaf手动渲染页面在spring4 和 spring5下有些不一样的地方:
spring4下
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
@Autowired
private ThymeleafViewResolver thymeleafViewResolver;
SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(), request.getLocale(),model.asMap(), applicationContext);
// 手动渲染
String html = thymeleafViewResolver.getTemplateEngine().process("这里写html页面名称", ctx);
spring5下
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
@Autowired
private ThymeleafViewResolver thymeleafViewResolver;
WebContext ctx = new WebContext(request,response,request.getServletContext(),request.getLocale(),model.asMap());
// 手动渲染
String html = thymeleafViewResolver.getTemplateEngine().process("这里写html页面名称", ctx);
运行一下,查看redis中是否有数据:
1.2 压力测试
1000个线程,循环访问10次
结果:
二、对象缓存
比如说要经常查询用户信息,那么可以将用户信息放入到redis中,然后直接从redis中查询。
改造用户中心微服务,让其查询用户信息的时候不是直接从数据库中获取,先从redis中查询,查询不到的话再去数据库中查询,从数据库中查询到后再把数据放入到缓存当中。
2.1 用户信息查询
修改leyou-user-service中的queryUser验证用户方法:
/**
* 用户验证
* @param username
* @param password
* @return
*/
@Override
public User queryUser(String username, String password) {
/**
* 逻辑改变,先去缓存中查询用户数据,查到的话直接返回,查不到再去数据库中查询,然后放入到缓存当中
*/
//1.缓存中查询
BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(KEY_PREFIX+username);
User user = (User) hashOperations.get(username);
if (user == null){
//在缓存中没有查到,去数据库查,查到放入缓存当中
User record = new User();
record.setUsername(username);
user = this.userMapper.selectOne(record);
hashOperations.put(user.getUsername(),user);
}
//2.校验用户名
if (user == null){
return null;
}
//3. 校验密码
boolean result = CodecUtils.passwordConfirm(username + password,user.getPassword());
if (!result){
return null;
}
//4.用户名密码都正确
return user;
}
2.2. 用户信息修改
比如说提供修改用户密码的接口,那么在修改数据库时会产生一些问题。是先删除缓存,再更新数据库呢?还是先更新数据库再删除缓存?
试想,两个并发操作,一个是更新操作,另一个是查询操作,更新操作删除缓存后,查询操作没有命中缓存,先把老数据读出来后放到缓存中,然后更新操作更新了数据库。于是,在缓存中的数据还是老的数据,导致缓存中的数据是脏的,而且还一直这样脏下去了。
所以,应该先更新数据库然后再删除缓存。
Cache Aside Pattern
-
失效:应用程序先从cache取数据,没有得到,则从数据库中取数据,成功后,放到缓存中。
-
命中:应用程序从cache中取数据,取到后返回。
-
更新:先把数据存到数据库中,成功后,再让缓存失效。
具体代码:
/**
* 根据用户名修改密码
* @param username
* @param newPassword
* @return
*/
@Override
public boolean updatePassword(String username,String oldPassword, String newPassword) {
/**
* 这里面涉及到对缓存的操作:
* 先把数据存到数据库中,成功后,再让缓存失效。
*/
//1.读取用户信息
User user = this.queryUser(username,oldPassword);
if (user == null){
return false;
}
//2.更新数据库中的用户信息
User updateUser = new User();
updateUser.setId(user.getId());
//2.1密码加密
String encodePassword = CodecUtils.passwordBcryptEncode(username.trim(),newPassword.trim());
updateUser.setPassword(encodePassword);
this.userMapper.updateByPrimaryKeySelective(updateUser);
//3.处理缓存中的信息
BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(KEY_PREFIX+username);
hashOperations.delete(username);
return true;
}
三、页面静态化
静态化是指把动态生成的HTML页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。而静态的HTML页面可以部署在nginx中,从而大大提高并发能力,减小tomcat压力。
使用Thymeleaf模板引擎实现静态化。
3.1 概念
先说下Thymeleaf中的几个概念:
-
Context:运行上下文
-
TemplateResolver:模板解析器
-
TemplateEngine:模板引擎
Context
上下文: 用来保存模型数据,当模板引擎渲染时,可以从Context上下文中获取数据用于渲染。
当与SpringBoot结合使用时,我们放入Model的数据就会被处理到Context,作为模板渲染的数据使用。
TemplateResolver
模板解析器:用来读取模板相关的配置,例如:模板存放的位置信息,模板文件名称,模板文件的类型等等。
当与SpringBoot结合时,TemplateResolver已经由其创建完成,并且各种配置也都有默认值,比如模板存放位置,其默认值就是:templates。比如模板文件类型,其默认值就是html。
TemplateEngine
模板引擎:用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。然后利用内置的语法规则解析,从而输出解析后的文件。来看下模板引擎进行处理的函数:
templateEngine.process("模板名", context, writer);
三个参数:
-
模板名称
-
上下文:里面包含模型数据
-
writer:输出目的地的流
在输出时,我们可以指定输出的目的地,如果目的地是Response的流,那就是网络响应。如果目的地是本地文件,那就实现静态化了。
而在SpringBoot中已经自动配置了模板引擎,因此我们不需要关心这个。现在我们做静态化,就是把输出的目的地改成本地文件即可!
3.2 实现
package com.leyou.service.impl;
import com.leyou.service.GoodsHtmlService;
import com.leyou.service.GoodsService;
import com.leyou.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;
/**
* @Author: 98050
* @Time: 2018-10-19 09:46
* @Feature: 实现页面静态化接口
*/
@Service
public class GoodsHtmlServiceImpl implements GoodsHtmlService {
@Autowired
private GoodsService goodsService;
@Autowired
private TemplateEngine templateEngine;
private static final Logger LOGGER = LoggerFactory.getLogger(GoodsHtmlService.class);
@Override
public void createHtml(Long spuId) {
PrintWriter writer = null;
//获取页面数据
Map<String,Object> spuMap = this.goodsService.loadModel(spuId);
//创建Thymeleaf上下文对象
Context context = new Context();
//把数据放入上下文对象
context.setVariables(spuMap);
//创建输出流
File file = new File("D:\\nginx-1.12.2\\html\\item\\"+spuId+".html");
try {
writer = new PrintWriter(file);
//执行页面静态化方法
templateEngine.process("item",context,writer);
} catch (FileNotFoundException e) {
LOGGER.error("页面静态化出错:{}"+e,spuId);
}finally {
if (writer != null){
writer.close();
}
}
}
/**
* 新建线程处理页面静态化
* @param spuId
*/
@Override
public void asyncExecute(Long spuId) {
ThreadUtils.execute(() ->createHtml(spuId));
}
@Override
public void deleteHtml(Long id) {
File file = new File("D:\\nginx-1.12.2\\html\\item\\"+id+".html");
file.deleteOnExit();
}
}
线程工具类:
package com.leyou.utils;
import java.util.concurrent.*;
/**
* @Author: 98050
* @Time: 2018-10-19 10:19
* @Feature: 线程工具
*/
public class ThreadUtils {
private static final ExecutorService es = Executors.newFixedThreadPool(10);
public static void execute(Runnable runnable){
es.submit(runnable);
}
}
3.3 什么时候创建静态文件
我们编写好了创建静态文件的service,那么问题来了:什么时候去调用它呢
场景描述:
假如大部分的商品都有了静态页面。那么用户的请求都会被nginx拦截下来,根本不会到达我们的leyou-goods-web
服务。只有那些还没有页面的请求,才可能会到达这里。
因此,如果请求到达了这里,我们除了返回页面视图外,还应该创建一个静态页面,那么下次就不会再来麻烦我们了。
所以,我们在GoodsController中添加逻辑,去生成静态html文件:
@GetMapping("{id}.html")
public String toItemPage(@PathVariable("id")Long id, Model model){
// 加载所需的数据
Map<String, Object> map = this.goodsService.loadModel(id);
// 把数据放入数据模型
model.addAllAttributes(map);
// 页面静态化
this.goodsHtmlService.asyncExcute(id);
return "item";
}
注意:生成html 的代码不能对用户请求产生影响,所以这里我们使用额外的线程进行异步创建。
3.4 nginx代理静态页面
server {
listen 80;
server_name www.leyou.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location /item {
# 先找本地
root html;
if (!-f $request_filename) { #请求的文件不存在,就反向代理
proxy_pass http://127.0.0.1:8084;
break;
}
}
location / {
proxy_pass http://127.0.0.1:9002;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
}