一 页面静态化消息分发 *****
1.1 生成者-PageService
**pom**
!-- 通过公共rabbitmq的模块引入mq的jar包-->
<dependency>
<groupId>cn.itsource</groupId>
<artifactId>hrm-basic-rabbitmq</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
**配置连接**
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtualHost: /
**RabbitTemplate**
PageConfigController
@PostMapping("/staticPage")
AjaxResult staticPage(@RequestBody Map<String, String> map){
String dataKey = map.get("dataKey");
String pageName = map.get("pageName");
try {
pageConfigService.staticPage(dataKey,pageName);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setSuccess(false).setMessage("静态化失败!"+e.getMessage());
}
}
@Override
public void staticPage(String dataKey, String pageName) {
FileOutputStream os = null;
InputStream is = null;
try {
Pager pager = pagerMapper
.selectList(new EntityWrapper<Pager>().eq("name", pageName)).get(0);
String templateUrl = pager.getTemplateUrl();
String templateName = pager.getTemplateName();
Response response =
fastDfsClient.download(templateUrl);
is = response.body().asInputStream();
String tmpdir=System.getProperty("java.io.tmpdir");
System.out.println(tmpdir+"jjjjj.........");
String zipPath = tmpdir+"/temp.zip";
String unZipPath = tmpdir + "/temp/";
os = new FileOutputStream(zipPath);
IOUtils.copy(is , os);
ZipUtil.unzip(zipPath,unZipPath);
String templatePath = unZipPath+"/"+templateName;
System.out.println(templatePath+"zz.........");
String templatePagePath = templatePath+".html";
System.out.println(templatePagePath+"xxx.........");
String courseTypes =redisClient.get("courseTypes");
List<CourseTypeDto> courseTypeDtos = JSONArray.parseArray(courseTypes,CourseTypeDto.class);
Map<String, Object> modelMap = new HashMap<>();
modelMap.put("staticRoot", unZipPath);
modelMap.put("courseTypes", courseTypeDtos);
VelocityUtils.staticByTemplate(modelMap,templatePath,templatePagePath);
String pageUrl = fastDfsClient.upload(
new CommonsMultipartFile(createFileItem(new File(templatePagePath),"file")));
PageConfig config = new PageConfig();
config.setTemplateUrl(templateUrl);
config.setTemplateName(templateName);
config.setDataKey(dataKey);
config.setPhysicalPath(pager.getPhysicalPath());
config.setDfsType(0L);
config.setPageUrl(pageUrl);
config.setPageId(pager.getId());
pageConfigMapper.insert(config);
String routingKey = siteMapper
.selectList(new EntityWrapper<Site>().eq("id", pager.getSiteId())).get(0).getSn();
System.out.println(routingKey+"ddh......");
JSONObject jsonObject = new JSONObject();
jsonObject.put("fileSysType",0);
jsonObject.put("staticPageUrl",pageUrl);
jsonObject.put("physicalPath",pager.getPhysicalPath());
System.out.println(jsonObject.toJSONString()+"dbl.....");
rabbitTemplate.convertAndSend(
RabbitmqConstants.EXCHANGE_DIRECT_INFORM,routingKey,jsonObject.toJSONString());
}catch (Exception e){
e.printStackTrace();
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private FileItem createFileItem(File file,String filedName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(filedName, "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
1.2 消费者-PageAgent
1)基本环境搭建
**pom**
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>cn.itsource</groupId>
<artifactId>hrm-basic-rabbitmq</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.itsource</groupId>
<artifactId>hrm-common-client</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
</dependencies>
**配置**
Bootstrap.yml
spring:
profiles:
active: dev
cloud:
config:
name: application-page-agent #github上面名称
profile: ${spring.profiles.active} #环境 java -jar -D xxx jar
label: master #分支
discovery:
enabled: true #从eureka上面找配置服务
service-id: hrm-config-server #指定服务名
#uri: http://127.0.0.1:1299 #配置服务器 单机配置
eureka: #eureka不能放到远程配置中
client:
service-url:
defaultZone: http://localhost:1010/eureka #告诉服务提供者要把服务注册到哪儿 #单机环境
instance:
prefer-ip-address: true #显示客户端真实ip
feign:
hystrix:
enabled: true #开启熔断支持
client:
config:
remote-service: #服务名,填写default为所有服务
connectTimeout: 3000
readTimeout: 3000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
配置库
server:
port: 2040
spring:
application:
name: hrm-page-agent
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtualHost: /
routingKey: hrmCourseSite
**入口类**
创建模块
Pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--配置中心支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- 通过公共rabbitmq的模块引入mq的jar包-->
<dependency>
<groupId>cn.itsource</groupId>
<artifactId>hrm-basic-rabbitmq</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- fastdfsclient支持-->
<dependency>
<groupId>cn.itsource</groupId>
<artifactId>hrm-common-client</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 给调用的模块来转换json-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson 调用者需要转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
</dependencies>
配置
Bootstrap.yml
spring:
profiles:
active: dev
cloud:
config:
name: application-page-agent #github上面名称
profile: ${spring.profiles.active} #环境 java -jar -D xxx jar
label: master #分支
discovery:
enabled: true #从eureka上面找配置服务
service-id: hrm-config-server #指定服务名
#uri: http://127.0.0.1:1299 #配置服务器 单机配置
eureka: #eureka不能放到远程配置中
client:
service-url:
defaultZone: http://localhost:1010/eureka #告诉服务提供者要把服务注册到哪儿 #单机环境
instance:
prefer-ip-address: true #显示客户端真实ip
feign:
hystrix:
enabled: true #开启熔断支持
client:
config:
remote-service: #服务名,填写default为所有服务
connectTimeout: 3000
readTimeout: 3000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
配置库
server:
port: 2040
spring:
application:
name: hrm-page-agent
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtualHost: /
routingKey: hrmCourseSite
入口类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class PageAgentApplication2040 {
public static void main(String[] args) {
SpringApplication.run(PageAgentApplication2040.class,args);
}
}
package cn.itsource.config;
import cn.itsource.util.RabbitMqConstants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMqConfig {
public static final String QUEUE_PAGE_STATIC = "queue_page_static";
public static final String EXCHANGE_TOPICS_PAGE = RabbitMqConstants.EXCHANGE_TOPICS_PAGE;
@Value("${rabbitmq.routingKey}")
private String routingKey;
@Bean(EXCHANGE_TOPICS_PAGE)
public Exchange EXCHANGE_TOPICS_INFORM() {
return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_PAGE).durable(true).build();
}
@Bean(QUEUE_PAGE_STATIC)
public Queue QUEUE_INFORM_SMS() {
Queue queue = new Queue(QUEUE_PAGE_STATIC);
return queue;
}
@Bean
public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_PAGE_STATIC) Queue queue,
@Qualifier(EXCHANGE_TOPICS_PAGE) Exchange exchange) {
System.out.println(routingKey+"jjjjjjjjjjjjjjj");
return BindingBuilder.bind(queue).to(exchange).with(routingKey).noargs();
}
}
Handler
@Component
public class StaticPageHandler {
@RabbitListener(queues = RabbitMqConfig.QUEUE_PAGE_STATIC)
public void handle(String msg, Message message, Channel channel){
System.out.println("接收消息:"+msg);
Map map = JSONObject.parseObject(msg, Map.class);
Integer fileSysType = (Integer) map.get(RabbitMqConstants.FILE_SYS_TYPE);
String pageUrl = (String) map.get(RabbitMqConstants.PAGE_URL);
String physicalPath = (String) map.get(RabbitMqConstants.PHYSICAL_PATH);
switch(fileSysType){
case 0 :
downloadAndCopyOfFastDfs(pageUrl,physicalPath);
break;
case 1 :
downloadAndCopyOfHdfs(pageUrl,physicalPath);
break;
}
}
@Autowired
private FastDfsClient fastDfsClient;
private void downloadAndCopyOfFastDfs(String pageUrl, String physicalPath) {
InputStream is = null;
FileOutputStream os = null;
try{
Response response = fastDfsClient.download(pageUrl);
is = response.body().asInputStream();
System.out.println(physicalPath);
os = new FileOutputStream(physicalPath);
IOUtils.copy(is,os) ;
}catch (Exception e){
e.printStackTrace();
}
finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void downloadAndCopyOfHdfs(String pageUrl, String physicalPath) {
}
}
``
1.3 数据发生改变重新页面静态化
课程类型增删改
# 二 课程列表页 *****
2.1 分析
1)入口
搜索框 类型导航
2)分析
只有类型导航进来的才有面包屑,但是两者都是高级查询+分页
2.2 实现
1)入口实现
调整是携带参数,页面进行解析,如果是关键字可以做回显
2)面包屑
List<Map> 有序表示层级,Map里面要放自己和兄弟。
@Override
public List<Map<String, Object>> getCrumbs(Long courseTypeId) {
List<Map<String,Object>> result = new ArrayList<>();
CourseType courseType = courseTypeMapper.selectById(courseTypeId);
String path = courseType.getPath();
String[] paths = path.split("\\.");
for (String ownerIdStr : paths) {
Map<String,Object> map = new HashMap<>();
Long ownerId = Long.valueOf(ownerIdStr);
System.out.println(ownerId);
CourseType owner = courseTypeMapper.selectById(ownerId);
map.put("owner",owner);
List<CourseType> allChildren = courseTypeMapper
.selectList(new EntityWrapper<CourseType>().eq("pid",owner.getPid()));
Iterator<CourseType> iterator = allChildren.iterator();
while (iterator.hasNext()){
CourseType currentType = iterator.next();
if (currentType.getId().longValue()==owner.getId().longValue()){
iterator.remove();
continue;
}
}
map.put("otherCourseTypes",allChildren);
result.add(map);
}
return result;
}
3)分页列表
dsl-基本结构
```java
@PostMapping("/queryCourses")
public PageList<Map<String,Object>> queryCourses(@RequestBody Map<String,Object> query){
System.out.println(query);
return courseService.queryCourses(query);
}
@Override
public PageList<Map<String, Object>> queryCourses(Map<String,Object> query) {
return esCourseClient.query(query);
}
EsClient
@PostMapping("/query")
PageList<Map<String,Object>> query(@RequestBody Map<String, Object> params){
return esCourseService.query(params);
}
@Override
public PageList<Map<String, Object>> query(Map<String, Object> params) {
String keyword = (String) params.get("keyword");
String sortField = (String) params.get("sortField");
String sortType = (String) params.get("sortType");
Long courseType = params.get("CourseType") !=null?Long.valueOf(params.get("CourseType").toString()):null;
Long priceMin = params.get("priceMin") !=null?Long.valueOf(params.get("priceMin").toString())*100:null;
Long priceMax = params.get("priceMax") !=null?Long.valueOf(params.get("priceMax").toString())*100:null;
Long page = params.get("page") !=null?Long.valueOf(params.get("page").toString()):null;
Long rows = params.get("rows") !=null?Long.valueOf(params.get("rows").toString()):null;
NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if (StringUtils.isNotBlank(keyword)){
boolQuery.must(QueryBuilders.matchQuery("all", keyword));
}
List<QueryBuilder> filter = boolQuery.filter();
if (courseType != null){
System.out.println(courseType+"jjjjjjjjjjjjjjjjjjj");
filter.add(QueryBuilders.termQuery("courseTypeId", courseType));
}
if(priceMax!=null &&priceMin != null){
filter.add(QueryBuilders.rangeQuery("price").gte(priceMin).lte(priceMax));
}
builder.withQuery(boolQuery);
SortOrder defaultSortOrder = SortOrder.DESC;
if (StringUtils.isNotBlank(sortField)){
if (StringUtils.isNotBlank(sortType) && !sortType.equals(SortOrder.DESC)){
defaultSortOrder = SortOrder.ASC;
}
if (sortField.equals("jg")){
builder.withSort(SortBuilders.fieldSort("price").order(defaultSortOrder));
}
}
Long pageTmp = page-1;
builder.withPageable(PageRequest.of(pageTmp.intValue(), rows.intValue()));
Page<EsCourse> CourseDocs = repository.search(builder.build());
List<Map<String,Object>> datas = esCourses2ListMap(CourseDocs.getContent());
return new PageList<>(CourseDocs.getTotalElements(),datas);
}
private List<Map<String,Object>> esCourses2ListMap(List<EsCourse> content) {
List<Map<String,Object>> result = new ArrayList<>();
for (EsCourse esCourse : content)
{
result.add(esCourse2Map(esCourse));
}
return result;
}
private Map<String,Object> esCourse2Map(EsCourse esCourse) {
Map<String,Object> result = new HashMap<>();
result.put("id", esCourse.getId());
result.put("name", esCourse.getName());
result.put("users", esCourse.getUsers());
result.put("courseTypeId", esCourse.getCourseTypeId());
result.put("courseTypeName", esCourse.getCourseTypeName());
result.put("gradeId", esCourse.getGradeId());
result.put("gradeName", esCourse.getGradeName());
result.put("status", esCourse.getStatus());
result.put("tenantId", esCourse.getTenantId());
result.put("tenantName", esCourse.getTenantName());
result.put("userId", esCourse.getUserId());
result.put("userName", esCourse.getUserName());
result.put("startTime", esCourse.getStartTime());
result.put("endTime", esCourse.getEndTime());
result.put("expires", esCourse.getExpires());
result.put("priceOld", esCourse.getPriceOld());
result.put("price", esCourse.getPrice());
result.put("intro", esCourse.getIntro());
result.put("qq", esCourse.getQq());
result.put("resources", esCourse.getResources());
return result;
}