1、IShortUrlService 接口类

public interface IShortUrlService {/*** 生成短链** @param shortUrlRequest* @return*/String shortUrlGenerator(ShortUrlRequest shortUrlRequest);/*** 根据短链获取完整链接** @param shortUrl* @return*/String getUrl(String shortUrl);/*** 增加短链点击量** @param shortUrl* @return*/Boolean addClickCount(String shortUrl);
}

2、ShortUrlServiceImpl 接口实现类

@DubboService
public class ShortUrlServiceImpl implements IShortUrlService {private static final Logger log = LoggerFactory.getLogger(ShortUrlServiceImpl.class);@Resourceprivate RedisTemplate<String, String> redisTemplate;@Resourceprivate ShortUrlMapper shortUrlMapper;@Resourceprivate SpringApplicationContext springApplicationContext;/*** 域名匹配正则表达式*/private static final Pattern DOMAIN_NAME_PATTERN = Pattern.compile("http(s)?://[\\w-]+[.\\w-]+(/)?");@Overridepublic String shortUrlGenerator(ShortUrlRequest shortUrlRequest) {String fullUrl = shortUrlRequest.getFullUrl();if (ObjectUtils.isEmpty(fullUrl)) {throw new BaseException(500, "链接不能为空");}String[] shortUrls = ShortUrlUtil.generator(fullUrl);for (String shortUrl : shortUrls) {// 判断短链是否已存在String url = springApplicationContext.getBean(IShortUrlService.class).getUrl(shortUrl);if (url != null) {if (!url.equals(shortUrlRequest.getFullUrl())) {continue;}return shortUrl;}// 保存长链接与短链接短对应关系ShortUrl shortUrlEntity = new ShortUrl();shortUrlEntity.setFullUrl(fullUrl);shortUrlEntity.setShotCode(shortUrl);shortUrlEntity.setExpirationDate(shortUrlRequest.getExpirationDate());Matcher matcher = DOMAIN_NAME_PATTERN.matcher(fullUrl);if (!matcher.find()) {throw new BaseException(500, "链接解析失败");}String baseUrl = matcher.group();shortUrlEntity.setBaseUrl(baseUrl);shortUrlEntity.setSuffixUrl(fullUrl.substring(baseUrl.length() - 1));shortUrlMapper.insert(shortUrlEntity);return shortUrl;}throw new BaseException(500, "链接生成失败");}@Override@Cacheable(cacheNames = "shortUrl", key = "#shortUrl", unless = "#result == null")public String getUrl(String shortUrl) {QueryWrapper<ShortUrl> shortUrlQw = new QueryWrapper<>();shortUrlQw.eq("shot_code", shortUrl);shortUrlQw.eq("del_flag", DelFlag.NORMAL);ShortUrl url = shortUrlMapper.selectOne(shortUrlQw);return url == null ? null : url.getFullUrl();}@Override@Transactional(rollbackFor = Exception.class)public Boolean addClickCount(String shortUrl) {QueryWrapper<ShortUrl> shortUrlQw = new QueryWrapper<>();shortUrlQw.eq("shot_code", shortUrl);shortUrlQw.eq("del_flag", DelFlag.NORMAL);ShortUrl url = shortUrlMapper.selectOne(shortUrlQw);if (url == null) {return false;}url.setTotalClickCount(url.getTotalClickCount() + 1);return shortUrlMapper.updateById(url) > 0;}@Scheduled(cron = "0 0 3 * * * ")public void removeShortUrl() {QueryWrapper<ShortUrl> queryWrapper = new QueryWrapper<>();queryWrapper.le("expirationDate", DateUtil.getTime());List<ShortUrl> shortUrls = shortUrlMapper.selectList(queryWrapper);//删除缓存数据库
//        for (ShortUrl shortUrl : shortUrls) {
//            redisTemplate.delete(shortUrl.getShotCode());
//        }List<Long> shortUrlIds = shortUrls.stream().map(ShortUrl::getId).collect(Collectors.toList());//删除mysql数据库shortUrlMapper.deleteBatchIds(shortUrlIds);
//        try {
//            Thread.sleep(1000);
//            //再次删除缓存数据库
//            for (ShortUrl shortUrl : shortUrls) {
//                redisTemplate.delete(shortUrl.getShotCode());
//            }
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }}
}

3、ShortUrlHandler 工具类

public class ShortUrlHandler implements Runnable{private final IShortUrlService  shortUrlService;private final String shortUrl;public ShortUrlHandler(IShortUrlService shortUrlService, String shortUrl) {this.shortUrlService = shortUrlService;this.shortUrl = shortUrl;}@Overridepublic void run() {shortUrlService.addClickCount(shortUrl);}
}

4、ShortUrlController 控制器类

@RestController
@RequestMapping("/api/shortUrl")
@Api(tags = {"C端-短链接"})
@RefreshScope
public class ShortUrlController extends BaseController {@DubboReferenceprivate IShortUrlService shortUrlService;@Resourceprivate ThreadPoolTaskExecutor threadPoolTaskExecutor;//short-utl://    prefix: http://test.gateway.yaotiao.net/coupon-provider/api/shortUrl/redirect/@Value("${short-utl.prefix:https://gateway.jumituangou.com/coupon-provider/api/shortUrl/redirect/}")private String prefixUrl;@GetMapping("/generator")@ApiOperation("生成短链")public ResponseResult<String> shortUrlGenerator(ShortUrlRequest shortUrlRequest) {shortUrlRequest.setExpirationDate(DateUtil.getDateAfterDay(new Date(), 60));String shortUrl = prefixUrl + shortUrlService.shortUrlGenerator(shortUrlRequest);return success(shortUrl);}@GetMapping("/redirect/{shortUrl}")@ApiOperation("短链重定向")@IgnoreUrlsAnnon("/api/shortUrl/") //白名单public void redirect(@PathVariable String shortUrl, HttpServletResponse response) {String url = shortUrlService.getUrl(shortUrl);try {response.sendRedirect(url);} catch (IOException e) {e.printStackTrace();}// 异步增加短链点击次数ShortUrlHandler shortUrlHandler = new ShortUrlHandler(shortUrlService, shortUrl);threadPoolTaskExecutor.execute(shortUrlHandler);}
}

5、mysql 表 short_url;

Java之SpringBoot短链接生成相关推荐

  1. java 新浪短链接_java高仿新浪微博短链接地址生成工具ShortUrlGenerator.java | 学步园...

    仿新浪微博 短链接地址生成工具 ShortUrlGenerator.java String sLongUrl = "http://www.zuidaima.com/share/1550463 ...

  2. java 新浪短链接_新浪(t.cn)短网址链接生成api接口

    最新的新浪(t.cn)短网址生成api接口,快速生成t.cn超短链接,接口可以正常调用,觉得不错可以收藏一下. 新浪短网址api接口: 使用说明: 将api接口地址中 "http://www ...

  3. Java调用百度短网址生成短链接

    1. 方式一 直接在线生成 https://dwz.cn/ 2. 方式二 调用接口生成 引入gson-2.8.5.jar 可以通过maven仓库搜索下载地址 http://central.maven. ...

  4. 新浪短网址api接口 - t.cn 短链接生成

    简要描述 新浪短网址api接口是新浪官方对外公开的t.cn短链接生成接口,可以将一个冗长的链接缩短生成t.cn/xxxx 格式的短链接. 应用场景 短网址的应用场景很广,譬如短信营销.邮件推广.微信营 ...

  5. java 新浪短链接_2020最新的新浪短网址(T.CN短链接)API接口分享

    还记得一年前,因为一个客户委托我们开发了一个新浪短网址API接口!原本这个T.cn的短链接接口一直是我们自己和委托开发的客户在使用! 但是由于前段时间,新浪关闭了之前开放的T.CN短链接接口!有好多客 ...

  6. java 新浪短链接_新浪短链接/腾讯短链接的API接口分享(含调用代码)

    最新好多朋友需要使用腾讯/新浪的官方短连接api接口,但是自己无法获取,或者说现有的API接口不支持现在的高频率调用,今天我就分享几个新浪/腾讯短域名的API接口给大家使用! 短链接他的目的就是将冗长 ...

  7. t.cn新浪短链接 生成

    新浪高价短域名t.cn正式跳转微博登录页面.域名t.cn已经实现t.sina.com.cn的切换,用户可以输入t.cn访问网站,手机用户也 可以直接通过t.cn访问新浪微博,用户微博地址原先为t.si ...

  8. php短链接生成,短链接api

    话不多说,直接上干货,http://www.m58.link/ 免费提供直接转和api转,还有个性化跳转,密码跳转等,简直不要太好用. 1.直接转: 进网页直接输入长网址,然后点shorten直接转 ...

  9. java 新浪短链接_短网址链接生成器代码示例——新浪短链接api接口php、java、Python调用演示...

    短网址api对接成了大家经常遇到的难题,今天以t.cn短链接api接口为例给出三种语言的调用示例代码: 1.APIKEY获取: 2.调用代码 PHP调用代码 $url = 'http://www.ba ...

最新文章

  1. python 一张图画多条线_Gnuplot.py在一张图上绘制多条线
  2. 4701年新年快乐!
  3. linux终端运行pytorch,Linux虚拟机测试pytorch运行
  4. 个人信息泄露致电信诈骗猖獗 专家:治理亟须完善立法
  5. Go 语言编程 — 作用域
  6. 算法岗一片红海,如何选择适合自己的方向?
  7. Hibernate中的inverse属性和cascade属性
  8. Lua的require机制
  9. mysql isnull
  10. 【数据库系统】文件处理系统和DBMS的主要区别
  11. 【华为云分享】机器学习笔记(七) ---- 贝叶斯分类
  12. 解密android日志xlog,XLog 详解及源码分析
  13. HDU 4069 Squiggly Sudoku
  14. .net中对象序列化技术
  15. 读取和修改caffemodel文件
  16. Cisco Packet Tracer思科模拟器中OSPF动态路由配置
  17. html代码学习离线文档,新手学HTML代码的简易方法
  18. 简单的 thymeleaf 前端网页模板
  19. 蔡学镛:KPI心理学
  20. 点播和播放器下载需要的参数的区别(VideoId、AccessKeyId、AccessKeySecret、playKey、playauth)...

热门文章

  1. 检测浏览器无痕模式下是否支持localStorage
  2. Spring缺少aspectjweaver.jar异常
  3. MFC - LNK2001 “无法解析的外部符号”的几种情况及解决办法
  4. Spring Boot+Vue项目打包部署
  5. Handler源码分析 - Java层
  6. git上传代码和下载代码
  7. 自学java编译老是出错_编写HelloWorld程序编译时提示写入HelloWorld时出错是什么意思...
  8. 秋招硬件设计岗,offer拿到手软,是一种什么体验?
  9. mac电脑删除多余输入法
  10. SqlServer的LDF文件丢失, 如何仅用MDF文件恢复数据库呢?(已解决)