Spring Boot集成sitemapgen4j实现网站地图生成

1.什么是sitemapgen4j

是一个用于在Java中生成XML网站地图的库,比如生成网站的sitemap,如果超出了 5 万条需要写入另外一个 sitemap 当中,这个功能 sitemapgen4j 已经替我们实现了,无需担心。

sitemap

站点地图是网站管理员向搜索引擎告知其网站上可用于抓取的页面的一种简单方法。 站点地图最简单的形式是一个 XML 文件,其中列出了站点的 URL 以及有关每个 URL 的附加元数据(上次更新时间、通常更改的频率以及相对于站点中其他 URL 的重要性) )以便搜索引擎能够更智能地抓取网站。 网络爬虫通常通过网站内的链接和其他网站发现页面。 站点地图补充了此数据,以允许支持站点地图的爬网程序拾取站点地图中的所有 URL,并使用关联的元数据了解这些 URL。 使用 Sitemap 协议并不能保证网页被搜索引擎收录,但可以为网络爬虫提供提示,以更好地爬行您的网站。 Sitemap 0.90 根据 Attribution-ShareAlike Creative Commons License 的条款提供,并得到广泛采用,包括 Google、Yahoo! 和 Microsoft 的支持。Sitemap 是网站管理员向搜索引擎通知其网站上可用页面的一种简单方法 用于爬行。 站点地图最简单的形式是一个 XML 文件,其中列出了站点的 URL 以及有关每个 URL 的附加元数据(上次更新时间、通常更改的频率以及相对于站点中其他 URL 的重要性) )以便搜索引擎能够更智能地抓取网站。

2.代码工程

实验目的:生成网站地图

pom.xml

http 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>


    <artifactId>sitemap</artifactId>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.dfabulich</groupId>
            <artifactId>sitemapgen4j</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
</project>

application.yaml

http 复制代码
server:
  port: 8088

job

http 复制代码
package com.et.sitemap.job;


import com.redfin.sitemapgenerator.SitemapIndexGenerator;
import com.redfin.sitemapgenerator.W3CDateFormat;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author liuhaihua
 * @version 1.0
 * @ClassName SiteMapJob
 * @Description todo
 * @date 2024年04月25日 17:44
 */
@Component
public class SiteMapJob {
    private Logger log = LoggerFactory.getLogger(getClass());


    //@Scheduled(cron = "0 0 0 * * ?")
    @Scheduled(initialDelay = 1000,fixedRate = 10000)
    public void generateSitemap() {
        log.info("start generate sitemap");
        String tempPath = "D://tmp/";
        File file = new File(tempPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String domain = "http://www.liuhaihua.cn";
        try {
            WebSitemapGenerator g1 = WebSitemapGenerator.builder(domain, file)
                    .fileNamePrefix("article").build();
            Date date = new Date();
            for (int i = 1; i < 160000; i++) {
                WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/article/" + i).lastMod(date).build();
                g1.addUrl(url);
            }


            WebSitemapGenerator g2 = WebSitemapGenerator.builder(domain, file)
                    .fileNamePrefix("tag").build();
            Date date2 = new Date();
            for (int i = 1; i < 21; i++) {
                WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/tag/" + i).lastMod(date2).build();
                g2.addUrl(url);
            }


            WebSitemapGenerator g3 = WebSitemapGenerator.builder(domain, file)
                    .fileNamePrefix("type").build();
            Date date3 = new Date();
            for (int i = 1; i < 21; i++) {
                WebSitemapUrl url = new WebSitemapUrl.Options(domain + "/type/" + i).lastMod(date3).build();
                g3.addUrl(url);
            }


            List<String> fileNames = new ArrayList<>();


            // 生成 sitemap 文件
            List<File> articleFiles = g1.write();
            articleFiles.forEach(e -> fileNames.add(e.getName()));
            List<File> tagFiles = g2.write();
            tagFiles.forEach(e -> fileNames.add(e.getName()));
            List<File> typeFiles = g3.write();
            typeFiles.forEach(e -> fileNames.add(e.getName()));


            // 构造 sitemap_index 生成器
            W3CDateFormat dateFormat = new W3CDateFormat(W3CDateFormat.Pattern.DAY);
            SitemapIndexGenerator sitemapIndexGenerator = new SitemapIndexGenerator
                    .Options(domain, new File(tempPath + "sitemap_index.xml"))
                    .dateFormat(dateFormat)
                    .autoValidate(true)
                    .build();


            fileNames.forEach(e -> {
                try {
                    // 组装 sitemap 文件 URL 地址
                    sitemapIndexGenerator.addUrl(domain + "/" + e);
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
            });


            // 生成 sitemap_index 文件
            sitemapIndexGenerator.write();
            log.info("end generate sitemap");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

DemoApplication.java

java 复制代码
package com.et.sitemap;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;


@SpringBootApplication
@EnableScheduling
public class DemoApplication {


   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

3.测试

  • 启动spring boot应用

  • 查看生成的文件

4.参考引用

相关推荐
fat house cat_16 分钟前
【redis】线程IO模型
java·redis
草捏子19 分钟前
状态机设计:比if-else优雅100倍的设计
后端
stein_java1 小时前
springMVC-10验证及国际化
java·spring
weixin_478689761 小时前
C++ 对 C 的兼容性
java·c语言·c++
LUCIAZZZ2 小时前
HikariCP数据库连接池原理解析
java·jvm·数据库·spring·springboot·线程池·连接池
考虑考虑2 小时前
Springboot3.5.x结构化日志新属性
spring boot·后端·spring
涡能增压发动积2 小时前
一起来学 Langgraph [第三节]
后端
sky_ph2 小时前
JAVA-GC浅析(二)G1(Garbage First)回收器
java·后端
涡能增压发动积2 小时前
一起来学 Langgraph [第二节]
后端
TTDreamTT2 小时前
SpringBoot十二、SpringBoot系列web篇之过滤器Filte详解
spring boot