springboot新浪微博短链接生成 redis缓存5分钟
作者:互联网
ShortUrlUtil
package com.ljzforum.platform.util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
public class ShortUrlUtil {
protected static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);
/**
* 获取短链接url
* */
public static String getShortUrl(String url){
if(StringUtils.isBlank(url)){
return "";
}
try {
url=URLEncoder.encode(url, "UTF-8");
String requestUrl="http://api.t.sina.com.cn/short_url/shorten.json?source=2849184197&url_long="+url;
HttpClient httpClient = new HttpClient();
String data = httpClient.sendGet(requestUrl);
if(StringUtils.isBlank(data)){
data = httpClient.sendGet(requestUrl);
}
if(StringUtils.isBlank(data)){
return "";
}
JSONArray jsonArray =JSONArray.fromObject(data);
JSONObject jsonObject =(JSONObject) jsonArray.get(0);
String shortUrl = jsonObject.getString("url_short");
if(shortUrl.equals("http://t.cn/")){
return url;
}else{
return shortUrl;
}
} catch (Exception e) {
logger.error("获取短链接url失败 url="+url);
}
return url;
}
public static void main(String[] args) {
String url=getShortUrl("http://www.baidu.com");
System.out.println(url);
}
}
redis缓存5分钟
@Autowired
private RedisTemplate redisTemplate;
/**
* 将链接缓存5分钟
*/
private String activityShortUrl(Integer id){
String shortUrl = "";
String urlKey = “PARTNER:SHORTURL:”+id;
if (redisTemplate.hasKey(urlKey)) {
shortUrl = (String) redisTemplate.opsForValue().get(urlKey);
return shortUrl;
}
shortUrl = ShortUrlUtil.getShortUrl("你的长链接");
if (StringUtils.isNotBlank(shortUrl) && !shortUrl.equals("http://t.cn/")) {
redisTemplate.opsForValue().set(urlKey, shortUrl, 5, TimeUnit.MINUTES);
}
return shortUrl;
}
参考文章:
https://www.sojson.com/blog/330.html
https://blog.csdn.net/Kindle_code/article/details/77098007
标签:return,springboot,url,redis,shortUrl,import,data,微博短,String 来源: https://blog.csdn.net/qq_39313596/article/details/100554450