商品详情 动态展示 jsp+redis
http://localhost:8086/item/163282182263491.html
.html 伪静态化设置
web.xml
<!-- 前端控制器 -->
<servlet>
<servlet-name>taotao-item-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>taotao-item-web</servlet-name>
<!-- 伪静态化 -->
<url-pattern>*.html</url-pattern>
</servlet-mapping>
缓存添加分析
业务逻辑:
1、根据商品id到缓存中命中
2、查到缓存,直接返回。
3、查不到,查询数据库
4、把数据放到缓存中
5、返回数据
缓存中缓存热点数据,提供缓存的使用率。需要设置缓存的有效期。一般是一天的时间,可以根据实际情况跳转。
需要使用String类型来保存商品数据。
可以加前缀方法对象redis中的key进行归类。
ITEM_INFO:123456:BASE
ITEM_INFO:123456:DESC
如何把二维表保存到redis中:
1、表名就是第一层
2、主键是第二层
3、字段名第三次
三层使用“:”分隔作为key,value就是字段中的内容。
代码实现
applicationContext-redis.xml
<context:annotation-config/>
<!-- redis单机版 -->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="192.168.25.175"/>
<constructor-arg name="port" value="6379"/>
</bean>
<bean id="jedisClientPool" class="com.taotao.jedis.JedisClientPool"/>
ItemServiceImpl.getItemById
@Override
public TbItem getItemById(long itemId) {
//查询数据库之前先查询缓存
try {
String json = jedisClient.get(ITEM_INFO + ":" + itemId + ":BASE");
if (StringUtils.isNotBlank(json)) {
// 把json数据转换成pojo
TbItem tbItem = JsonUtils.jsonToPojo(json, TbItem.class);
System.out.println("cache-base-out:"+json);
return tbItem;
}
} catch (Exception e) {
e.printStackTrace();
}
//缓存中没有查询数据库
TbItem item = itemMapper.selectByPrimaryKey(itemId);
try {
//把查询结果添加到缓存
jedisClient.set(ITEM_INFO + ":" + itemId + ":BASE", JsonUtils.objectToJson(item));
//设置过期时间,提高缓存的利用率
jedisClient.expire(ITEM_INFO + ":" + itemId + ":BASE", TIEM_EXPIRE);
} catch (Exception e) {
e.printStackTrace();
}
return item;
}
freemarker 网页静态化
可以使用Freemarker实现网页静态化
FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。
目前企业中:主要用Freemarker做静态页面或是页面展示
Freemarker的使用方法
maven
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
原理
使用步骤:
第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
第二步:设置模板文件所在的路径。
第三步:设置模板文件使用的字符集。一般就是utf-8.
第四步:加载一个模板,创建一个模板对象。
第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
第七步:调用模板对象的process方法输出文件。
第八步:关闭流。
代码示例 student.ftl
student.ftl
<html>
<head>
<title>测试页面</title>
</head>
<body>
学生信息:<br>
学号:${student.id}<br>
姓名:${student.name}<br>
年龄:${student.age}<br>
家庭住址:${student.address}<br>
学生列表:<br>
<table border="1">
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>家庭住址</th>
</tr>
<#list stuList as stu>
<#if stu_index%2==0>
<tr bgcolor="red">
<#else>
<tr bgcolor="blue">
</#if>
<td>${stu_index}</td>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.address}</td>
</tr>
</#list>
</table>
<br>
日期类型的处理:${date?string("yyyy/MM/dd HH:mm:ss")}
<br>
null值的处理:${val!}
<br>
使用if判断null值:
<#if val??>
val是有值的。。。
<#else>
val值为null。。。
</#if>
<br>
include标签测试:
<#include "hello.ftl">
</body>
</html>
Student
package com.taotao.freemarker;
public class Student {
public Student(int id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public Student() {
}
private int id;
private String name;
private int age;
private String address;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
TestFreeMarker
package com.taotao.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class TestFreeMarker {
@Test
public void testFreemarker() throws Exception {
//1.创建一个模板文件
//2.创建一个Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//3.设置模板所在的路径
//configuration.setDirectoryForTemplateLoading(new File("D:/workspaces-itcast/JavaEE28/taotao-item-web/src/main/webapp/WEB-INF/ftl"));
configuration.setDirectoryForTemplateLoading(new File("D:/java/javawork2/taotao-item-web/src/main/webapp/WEB-INF/ftl"));
//4.设置模板的字符集,一般utf-8
configuration.setDefaultEncoding("utf-8");
//5.使用Configuration对象加载一个模板文件,需要指定模板文件的文件名。
// Template template = configuration.getTemplate("hello.ftl");
Template template = configuration.getTemplate("student.ftl");
//6.创建一个数据集,可以是pojo也可以是map,推荐使用map
Map data = new HashMap<>();
data.put("hello", "hello freemarker");
Student student = new Student(1, "小米", 11, "北京昌平回龙观");
data.put("student", student);
List<Student> stuList = new ArrayList<>();
stuList.add(new Student(1, "小米", 11, "北京昌平回龙观"));
stuList.add(new Student(2, "小米2", 12, "北京昌平回龙观"));
stuList.add(new Student(3, "小米3", 13, "北京昌平回龙观"));
stuList.add(new Student(4, "小米4", 14, "北京昌平回龙观"));
stuList.add(new Student(5, "小米5", 15, "北京昌平回龙观"));
stuList.add(new Student(6, "小米6", 16, "北京昌平回龙观"));
stuList.add(new Student(7, "小米7", 17, "北京昌平回龙观"));
data.put("stuList", stuList);
//日期类型的处理
data.put("date", new Date());
data.put("val","123456");
//7.创建一个Writer对象,指定输出文件的路径及文件名。
//Writer out = new FileWriter(new File("D:/temp/javaee28/out/student.html"));
Writer out = new FileWriter(new File("D:/java/spring/taotaoshop/item/out/student.html"));
//8.使用模板对象的process方法输出文件。
template.process(data, out);
//9.关闭流
out.close();
}
}
Freemarker整合spring
maven
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
springmvc.xml
<!-- freemarker的配置 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
HtmlGenController
业务逻辑:
1、从spring容器中获得FreeMarkerConfigurer对象。
2、从FreeMarkerConfigurer对象中获得Configuration对象。
3、使用Configuration对象获得Template对象。
4、创建数据集
5、创建输出文件的Writer对象。
6、调用模板对象的process方法,生成文件。
7、关闭流。
package com.taotao.item.controller;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* 网页静态处理Controller
* <p>Title: HtmlGenController</p>
* <p>Description: </p>
* <p>Company: www.itcast.cn</p>
* @version 1.0
*/
@Controller
public class HtmlGenController {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/genhtml")
@ResponseBody
public String genHtml() throws Exception {
//生成静态页面
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Template template = configuration.getTemplate("hello.ftl");
Map data = new HashMap<>();
data.put("hello", "spring freemarker test");
Writer out = new FileWriter(new File("D:/java/spring/taotaoshop/item/out/test.html"));
template.process(data, out);
out.close();
//返回结果
return "OK";
}
}
商品详情页面静态化
输出文件的名称:商品id+“.html”
输出文件的路径:工程外部的任意目录。
网页访问:使用nginx访问网页。在此方案下tomcat只有一个作用就是生成静态页面。
工程部署:可以把taotao-item-web部署到多个服务器上。
生成静态页面的时机:商品添加后,生成静态页面。可以使用Activemq,订阅topic(商品添加)
架构图
activeMQ同步生成静态页面
Freemaker生成静态页面的时机
添加商品后使用activemq广播消息,freemaker监听到消息去数据库查询商品生成静态页面
代码示例
ItemAddMesssageListener
package com.taotao.item.listener;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.taotao.item.pojo.Item;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class ItemAddMesssageListener implements MessageListener {
@Autowired
private ItemService itemService;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Value("${HTML_OUT_PATH}")
private String HTML_OUT_PATH;
@Override
public void onMessage(Message message) {
try {
//从消息中取商品id
TextMessage textMessage = (TextMessage) message;
String strId = textMessage.getText();
Long itemId = Long.parseLong(strId);
//等待事务提交
Thread.sleep(1000);
//根据商品id查询商品信息及商品描述
TbItem tbItem = itemService.getItemById(itemId);
Item item = new Item(tbItem);
TbItemDesc itemDesc = itemService.getItemDescById(itemId);
//使用freemarker生成静态页面
Configuration configuration = freeMarkerConfigurer.getConfiguration();
//1.创建模板
//2.加载模板对象
Template template = configuration.getTemplate("item.ftl");
//3.准备模板需要的数据
Map data = new HashMap<>();
data.put("item", item);
data.put("itemDesc", itemDesc);
//4.指定输出的目录及文件名
Writer out = new FileWriter(new File(HTML_OUT_PATH + strId + ".html"));
//5.生成静态页面
template.process(data, out);
//关闭流
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
springmvc-activemq.xml taotao-item-web
<!-- JMS服务厂商提供的ConnectionFactory -->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<constructor-arg name="brokerURL" value="tcp://192.168.25.175:61616"/>
</bean>
<!-- spring对象ConnectionFactory的封装 -->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory"></property>
</bean>
<bean id="itemAddTopic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg name="name" value="item-add-topic"></constructor-arg>
</bean>
<bean id="itemAddMessageListener" class="com.taotao.item.listener.ItemAddMesssageListener"/>
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory" />
<property name="destination" ref="itemAddTopic" />
<property name="messageListener" ref="itemAddMessageListener" />
</bean>