自学内容网 自学内容网

短链接功能实现

数据库

MySql

CREATE TABLE `short_link` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', 
  `create_id` bigint(20) DEFAULT NULL COMMENT '创建人',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `short_link_code` varchar(255) DEFAULT NULL, 
  `jump_path` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_short_link_code` (`short_link_code`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='短链接映射表';

nginx 设置

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen 3501; # 自行配置
        server_name 192.168.1.62 127.0.0.1; # 自行配置

        access_log  logs/3501.access.log; 

        location ~ ^/([a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9])$ {
            set $shortLink $1;
            rewrite ^ /shortLink/$shortLink permanent;
        }

    }
}

Java 服务

@RestController
@RequestMapping("/shortLink")
@Tag(name = "短链接")
public class ShortLinkController {


    @Resource
    private ShortLinkService shortLinkService;

    @GetMapping("/{shortLink}")
    @Operation(summary = "短链接重定向")
    public void shortLinkRedirect(@PathVariable("shortLink") String shortLink,
                                  HttpServletResponse response) throws IOException {

        ShortLink data = shortLinkService.getOne(
                Wrappers.lambdaQuery(ShortLink.class)
                        .eq(ShortLink::getShortLinkCode, shortLink)
        );
        if (data == null) {
            throw new ServiceException("链接无效!");
        }

        response.sendRedirect(data.getJumpPath());
    }

}

测试

插入数据

INSERT INTO  `short_link`(  `create_id`, `create_time`, `short_link_code`,   `jump_path`) VALUES (  23, '2025-01-15 16:42:28', '3lfaBU', 'http://www.baidu.com');

访问:http://192.168.1.62:3501/3lfaBU 会自动跳转至 http://www.baidu.com


原文地址:https://blog.csdn.net/Gemini1995/article/details/145164283

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!