Spring boot基于redis实现附近的人(附源码下载)

版权声明:本文为博主原创文章,转载请标明出处 https://blog.csdn.net/qq_19260029/article/details/82934081

此文章是针对去年写的Java基于Redis实现“附近的人 进行业务优化!

核心源码

public class NearbyPO {
	@NotNull(message = "id值不能为空")
	private Integer id;
	@NotBlank(message = "名称不能为空")
	private String name;
	@NotNull(message = "城市编码不能为空")
	private Integer cityCode;
	@NotNull(message = "地区编码不能为空")
	private Integer adCode;
	@NotNull(message = "经度不能为空")
	private Double longitude;
	@NotNull(message = "纬度不能为空")
	private Double latitude;

	/**
	 * 保存时间,不依赖前端传参
	 */
	private Long saveTime;
}
// 附近的人最新版
public Result<List<NearbyBO>> nearbyNew(NearbyPO paramObj) {
	// 缓存key值
	String cacheKey = String.format(NEARBY_CACHE_KEY, paramObj.getCityCode(), paramObj.getAdCode());
	long currentTimeMillis = System.currentTimeMillis();

	// 设置当前用户缓存时间
	paramObj.setSaveTime(currentTimeMillis);

	// 使用hash更加快速的定位到用户缓存信息,便于删除更新
	redisDao.hset(cacheKey, paramObj.getId() + "", JSONObject.toJSONString(paramObj));

	// 从当前地区缓存中获取全部用户(包括用户自己)
	Map<String, String> cacheAll = redisDao.hGetAll(cacheKey);
	if (cacheAll.isEmpty() || cacheAll.size() == 1) {
		return new Result<List<NearbyBO>>(true, new ArrayList<>());
	}

	// 结果集,-1是要排除用户自己
	List<NearbyBO> result = new ArrayList<NearbyBO>(cacheAll.size() - 1);

	for (String item : cacheAll.keySet()) {
		NearbyPO cacheData = JSONObject.parseObject(cacheAll.get(item), NearbyPO.class);

		// 计算缓存时长
		long twoDayMinute = (cacheData.getSaveTime() - currentTimeMillis) / 60000;
		// 八小时有效
		if (twoDayMinute > 480) {
			// 被动触发删除过期缓存
			redisDao.hdel(cacheKey, paramObj.getId() + "");
			continue;
		}
		// 排除用户自己
		if (paramObj.getId().equals(cacheData.getId())) {
			continue;
		}
		// 计算两坐标点距离
		double distance = countDistance(paramObj.getLongitude(), paramObj.getLatitude(), cacheData.getLongitude(),
				cacheData.getLatitude());
		// 10KM之内有效
		if (distance > 10000) {
			continue;
		}
		result.add(new NearbyBO(cacheData.getId(), cacheData.getName(), distance));
	}
	return new Result<List<NearbyBO>>(true, result);
}

源码下载(资源1分,包含去年的实现源码):https://download.csdn.net/download/qq_19260029/10701010
,没有积分的可评论留下邮箱私发。

测试访问地址:

  1. http://localhost:8080/nearby_new?id=1&name=不羁鱼&cityCode=440300&adCode=440305&longitude=113.9672334290&latitude=22.5829485425
  2. http://localhost:8080/nearby_new?id=2&name=王力宏&cityCode=440300&adCode=440305&longitude=113.9672334290&latitude=22.5229485425

end

推荐文章:
MyBatis基于Spring-boot集成通用Mapper以及pagehelper分页插件
RedisDesktopManager连接远程Linux系统的Redis服务
Spring boot基于Redis缓存商城分类,商品信息

猜你喜欢

转载自blog.csdn.net/qq_19260029/article/details/82934081
今日推荐