1.依赖包的引入
<!-- spring集成redis依赖 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
2.创建spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1" value="${redis.host}" type="String"/>
<constructor-arg index="2" value="${redis.port}" type="int" />
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- <property name="maxActive" value="${redis.pool.maxActive}" /> -->
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<!-- <property name="maxWait" value="${redis.pool.maxWait}" /> -->
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
</bean>
<bean id="redis" class="com.lantaiyuan.ebus.common.redis.RedisHelper">
<constructor-arg>
<ref bean="jedisPool" />
</constructor-arg>
</bean>
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="jedisPoolConfig" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.host}" />
<property name="timeout" value="${redis.timeout}"></property>
</bean>
<bean id="redisCacheConfig" class="com.lantaiyuan.ebus.common.redis.RedisCacheConfig" />
</beans>
3.在config.xml中配置redis相关信息
#redis配置
redis.pool.maxActive=300
redis.pool.maxIdle=100
redis.pool.maxWait=10000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
#redis配置地址
redis.host= 10.1.10.80
redis.port=6379
redis.timeout=60000
4.在spring-context.xml中引入spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 读入配置属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan
base-package="com.lantaiyuan.ebus.common.aop,com.lantaiyuan.ebus.custom.service,com.lantaiyuan.ebus.realtime.service,com.lantaiyuan.ebus.common.util" />
<bean id="myTaskTimerScanner" class="com.lantaiyuan.ebus.custom.scheme.TaskTimerScanner" />
<!-- 引入spring-redis.xml -->
<import resource="classpath:spring/spring-redis.xml" />
</beans>
5.配置文件中redis工具参考类
package com.lantaiyuan.ebus.common.redis;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisHelper {
private static Logger logger = Logger.getLogger(RedisHelper.class);
private static JedisPool jedisPool;
public RedisHelper(JedisPool pool) {
RedisHelper.jedisPool = pool;
}
public static String set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String rtn = jedis.set(key, value);
return rtn;
} catch(Exception e) {
logger.error("set方法报错:key=" + key + ",value=" + value, e);
throw new RuntimeException("set方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
public static String set(byte[] key, byte[] value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String rtn = jedis.set(key, value);
return rtn;
} catch(Exception e) {
logger.error("set方法报错:key=" + key + ",value=" + value, e);
throw new RuntimeException("set方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 根据key从redis删除相关值 */
public static void del(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
jedis.del(key);
} catch(Exception e) {
logger.error("del方法报错:key=" + key, e);
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 可以设置过期时间的set方法 */
public static String setWithExpireTime(String key, String value, int seconds) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
String rtn = jedis.set(key, value);
jedis.expire(key, seconds);
return rtn;
} catch(Exception e) {
logger.error("setWithExpireTime方法报错:key=" + key + ",value=" + value, e);
throw new RuntimeException("get方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 根据key从redis获取相关值 */
public static String get(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
String rtn = jedis.get(key);
return rtn;
} catch(Exception e) {
logger.error("get方法报错:key=" + key, e);
throw new RuntimeException("get方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/**
* 根据key从redis获取相关值
* @param key byte[]
* @return byte[]
*/
public static byte[] get(byte[] key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
byte[] rtn = jedis.get(key);
return rtn;
} catch(Exception e) {
logger.error("get方法报错:key=" + key, e);
throw new RuntimeException("get方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 往redis中设置map对象 */
public static String hmset(String key, Map<String, String> hash) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
String rtn = jedis.hmset(key, hash);
return rtn;
} catch(Exception e) {
logger.error("hmset方法报错:key=" + key, e);
throw new RuntimeException("hmset方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 从redis中获取map对象 */
public static Map<String, String> hgetall(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
Map<String, String> rtn = jedis.hgetAll(key);
return rtn;
} catch(Exception e) {
logger.error("hgetall方法报错:key=" + key, e);
throw new RuntimeException("hgetall方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 往redis中设置List对象 */
public static void setList(String key, List<String> list) {
if(list != null) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
jedis.del(key);
for (String str : list) {
jedis.rpush(key, str);
}
} catch(Exception e) {
logger.error("setList方法报错:key=" + key, e);
throw new RuntimeException("setList方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
}
/** 给特定key的值新增制定值,返回新增后该key的值 */
public static long incrBy(String key, long value) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
long rtn = jedis.incrBy(key, value);
return rtn;
} catch(Exception e) {
logger.error("incrBy方法报错:key=" + key + ",value=" + value, e);
throw new RuntimeException("incrBy方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 给特定key的值减少指定,返回修改后该key的值 */
public static long decrBy(String key, long value) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
long rtn = jedis.decrBy(key, value);
return rtn;
} catch(Exception e) {
logger.error("decrBy方法报错:key=" + key + ",value=" + value, e);
throw new RuntimeException("decrBy方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 判断key是否已经在缓存中存在 */
public static boolean isKeyExistSetWithExpire(String key, int seconds) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
long rtn = jedis.setnx(key, "1");
if(1 == rtn && seconds > 0) {
jedis.expire(key, seconds);
}
return rtn == 0;
} catch(Exception e) {
logger.error("isKeyExistSetWithExpire方法报错:key=" + key + ",seconds=" + seconds, e);
throw new RuntimeException("isKeyExistSetWithExpire方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 设置过期时间的方法 */
public static void expireByKey(String key, int seconds) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
if(seconds > 0) {
jedis.expire(key, seconds);
}
} catch(Exception e) {
logger.error("expireByKey方法报错:key=" + key + ",seconds=" + seconds, e);
throw new RuntimeException("expireByKey方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 判断key在缓存中是否存在 */
public static boolean isKeyExist(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch(Exception e) {
logger.error("isKeyExist方法报错:key=" + key, e);
throw new RuntimeException("isKeyExist方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 批量删除某些字符串开头的缓存 */
public static void batchDel(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
Set<String> set = jedis.keys(key +"*");
Iterator<String> it = set.iterator();
while(it.hasNext()){
String keyStr = it.next();
jedis.del(keyStr);
}
} catch(Exception e) {
logger.error("batchDel方法报错:key=" + key, e);
throw new RuntimeException("批量删除方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/** 批量查询某些字符串开头的缓存 */
public static void queryKeys(String key) {
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
Set<String> set = jedis.keys(key +"*");
Iterator<String> it = set.iterator();
while(it.hasNext()){
String keyStr = it.next();
System.out.println(keyStr);
}
} catch(Exception e) {
logger.error("queryKeys方法报错:key=" + key, e);
throw new RuntimeException("批量删除方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/**根据表达式查询redis中的key的集合 */
public static Set<String> keys(String pattern) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.keys(pattern);
} catch(Exception e) {
logger.error("keys方法报错:key=" + pattern, e);
throw new RuntimeException("keys方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/**获取hash key值下所有Item的key */
public static Set<String> hKeys(String pattern) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hkeys(pattern);
} catch(Exception e) {
logger.error("keys方法报错:key=" + pattern, e);
throw new RuntimeException("keys方法报错。");
} finally {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
}
6.redis缓存实现类
expires.put("nearStation", 120L);这边定义的KEY值“nearStation”在下一步中可以用到
package com.lantaiyuan.ebus.common.redis;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
*
* @Title: RedisCacheConfig.java
* @Package com.lantaiyuan.ebus.common.redis
* @Description: spring缓存配置文件
* @author 刘伟 15818570028@163.com
* @date 2017年3月25日 下午1:12:03
* @version V1.2.0
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(3000);
Map<String, Long> expires = new HashMap<>();
expires.put("nearStation", 120L);
cacheManager.setExpires(expires);
return cacheManager;
}
/**
* 自定义key. 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。
*/
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
7.缓存的使用
@CacheConfig(cacheNames="nearStation")标在类上面,表示该类中的缓存默认存储在redis中的nearStation域中,可以看成是缓存存储的命名空间
@Cacheable:标注在方法上,表示为该方法开启缓存
package com.lantaiyuan.ebus.custom.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.lanqiao.ssm.common.core.dao.BaseDAO;
import org.lanqiao.ssm.common.core.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.lantaiyuan.ebus.common.constants.SysGlobalConstants;
import com.lantaiyuan.ebus.common.util.GpsCorrectUtil;
import com.lantaiyuan.ebus.common.util.TimeUtils;
import com.lantaiyuan.ebus.custom.dao.BaseStationMapper;
import com.lantaiyuan.ebus.custom.model.BaseRoute;
import com.lantaiyuan.ebus.custom.model.BaseStation;
import com.lantaiyuan.ebus.custom.model.BaseStationQueryModel;
import com.lantaiyuan.ebus.custom.model.StationNameInfo;
import com.lantaiyuan.ebus.custom.service.BaseRouteServiceI;
import com.lantaiyuan.ebus.custom.service.BaseStationServiceI;
import com.lantaiyuan.ebus.realtime.model.BaseLine;
import com.lantaiyuan.ebus.realtime.model.NearStationsWithLine;
import com.lantaiyuan.ebus.realtime.model.RealTime;
import com.lantaiyuan.ebus.realtime.model.RealTimeQueryModel;
import com.lantaiyuan.ebus.realtime.model.RouteInBaseLine;
import com.lantaiyuan.ebus.realtime.model.StationAndBaseLines;
import com.lantaiyuan.ebus.realtime.model.StationNearInfo;
import com.lantaiyuan.ebus.realtime.service.TravelServiceI;
/**
* 描述:站点管理业务类 作者:温海金 最后更改时间:上午11:50:22 待修改
*/
@CacheConfig(cacheNames="nearStation")
@Service("baseStationService")
public class BaseStationServiceImpl extends BaseService<BaseStation, BaseStationQueryModel>
implements BaseStationServiceI {
@Resource
private BaseStationMapper baseStationMapper;
@Resource
private TravelServiceI travelServiceNew;;
@Resource
private BaseRouteServiceI baseRouteService;
@Override
public BaseDAO<BaseStation, BaseStationQueryModel> getDao() {
return baseStationMapper;
}
/**
* <p>
* Title: queryStationByName
* </p>
* <p>
* Description:
* </p>
*/
@Override
public BaseStation queryStationByName(String stationName, String cityCode) {
return baseStationMapper.queryStationByName(stationName, cityCode);
}
/**
* <p>
* Title: queryStationInfo
* </p>
* <p>
* Description:模糊查询车站信息
* </p>
*/
@Override
public List<StationNameInfo> queryStationInfo(String stationname, String citycode) {
return baseStationMapper.queryStationInfo(stationname, citycode);
}
/**
* <p>
* Title: getStationByName
* </p>
* <p>
* Description: 模糊查询站点信息
* </p>
*
* @author:liuhao
*/
@Override
public List<BaseStation> getStationByName(String stationName, String cityCode) {
return baseStationMapper.getStationByName(stationName, cityCode);
}
/**
* <p>
* Title: getStationByName
* </p>
* <p>
* Description: 根据stationId查询站点信息
* </p>
*
* @author:liuhao
*/
public BaseStation getStationById(String stationId, String cityCode) {
return baseStationMapper.getStationById(stationId, cityCode);
}
/**
* 根据站点id list,routeid,citycode,direction查出站点list
*
* @author yangyang
*/
@Override
public List<BaseStation> getStationsByIds(String routeId, String cityCode, int direction) {
return baseStationMapper.getStationsByIds(routeId, cityCode, direction);
}
/**
* 描述:获取当前站点附近的站点及线路信息 (原 最近站点&附近站点QueryController.java中的nearestStation接口)
* 作者:温海金 最后更改时间:上午11:50:22
*/
@Override
@Cacheable
public StationNearInfo getNearestInfo(BaseStation baseStation) {
// 对当前位置进行纠偏处理
correctOfGpsFromGaode2Google(baseStation);
// 1.获取附近站点,按距离从近到远排序
List<BaseStation> nearStations = baseStationMapper.getNearStations(baseStation,
SysGlobalConstants.TEN_DISTANCE);
if (nearStations.size() > 0) {
// 2.得到最近的站点
BaseStation nearestStation = nearStations.get(0);
// 3.对站点进行GPS纠偏处理
updataTheCorrectOfGps(nearestStation);
if (nearestStation.getDistance() == null) {
nearestStation.setDistance(new Double("0"));
}
if (nearestStation.getStationno() == null) {
nearestStation.setStationno(0);
}
// 4.得到附近的路线
List<BaseRoute> baseRoutes = baseRouteService.getRoutesByStationId(nearestStation.getStationid().toString(),
nearestStation.getCitycode(), TimeUtils.decideSeason());
List<BaseLine> lines = new ArrayList<>();// 线路信息
// 5.得到实时车辆信息
baseRoutes.forEach(baseRoute -> {
RouteInBaseLine routeInBaseLine = new RouteInBaseLine();
BeanUtils.copyProperties(baseRoute, routeInBaseLine);
RealTime busRealTimeInfo = getBusDetailInfo(baseStation.getCitycode(), nearestStation, baseRoute);
lines.add(new BaseLine(routeInBaseLine, busRealTimeInfo));
});
return new StationNearInfo(nearestStation == null ? new BaseStation() : nearestStation, lines,
nearStations);
}
return null;
}
/**
* 根据站点Id和城市编码查询站点信息
*
* @auther yangyang
* @param stationId
* @param cityCode
* @return
*/
private BaseStation getStationByStationId(String stationId, String cityCode) {
return baseStationMapper.getStationByStationId(stationId, cityCode);
}
/**
* 描述:查出包含5分钟和10分钟步行范围内的站点信息(包含经过该站点的线路信息) (原
* 附近站点(5min,10min)QueryController.java中的nearStationsFiveAndTen接口) 作者:温海金
* 最后更改时间:上午11:50:22
*/
@Override
@Cacheable
public Map<String, List<StationAndBaseLines>> nearStationsWithRouteFiveAndTen(BaseStation baseStation) {
// 对当前位置进行纠偏处理
correctOfGpsFromGaode2Google(baseStation);
// 1.获取步行10分钟内站点,按距离从近到远排序
List<BaseStation> stationsWithTen = baseStationMapper.getNearStations(baseStation,
SysGlobalConstants.TEN_DISTANCE);
// 2.获取步行5分钟内站点,按距离从近到远排序
List<BaseStation> stationsWithFive = getStationsWalkInFive(baseStation, stationsWithTen);
// 3.移除步行5分钟内的站点,得到步行距离从5分钟到10分钟范围的站点
stationsWithTen.removeAll(stationsWithFive);
// 4.纠偏处理
updataTheCorrectOfGps(stationsWithFive);
updataTheCorrectOfGps(stationsWithTen);
// 5.得到步行5分钟内的站点及线路信息
List<StationAndBaseLines> stationWithRouteInFive = getStationWithRouteInfo(baseStation.getCitycode(),
stationsWithFive);
// 6.得到步行5分钟到10分钟范围内的站点及线路信息
List<StationAndBaseLines> stationWithRouteInTen = getStationWithRouteInfo(baseStation.getCitycode(),
stationsWithTen);
Map<String, List<StationAndBaseLines>> stationBaseLinesIn5And10Map = new HashMap<>();
stationBaseLinesIn5And10Map.put("stationWithRouteInFive", stationWithRouteInFive);
stationBaseLinesIn5And10Map.put("stationWithRouteInTen", stationWithRouteInTen);
return stationBaseLinesIn5And10Map;
}
private void correctOfGpsFromGaode2Google(BaseStation station) {
if (station == null)
return;
double[] latlng= GpsCorrectUtil.gcj02_To_Gps84(station.getLatitude().doubleValue(), station.getLongitude().doubleValue());
station.setLatitude(BigDecimal.valueOf(latlng[0]));
station.setLongitude(BigDecimal.valueOf(latlng[1]));
}
/**
* 功能描述:从步行范围10分钟范围内的站点中过滤出步行范围5分钟的站点,避免再次查询数据库 作者:温海金 最后更改时间 : 2016年12月23日
* 下午5:26:04
*/
private List<BaseStation> getStationsWalkInFive(BaseStation curentStation, List<BaseStation> stationsWithTen) {
List<BaseStation> stationsWithFive = new ArrayList<>();
stationsWithTen.forEach(station -> {
if (station != null && travelServiceNew.isNearStation(station, curentStation.getLongitude().doubleValue(),
curentStation.getLatitude().doubleValue(), SysGlobalConstants.FIVE_DISTANCE)) {
stationsWithFive.add(station);
}
});
return stationsWithFive;
}
/**
* 功能描述:为集合中的每个站点添加线路及实时车辆信息 作者:温海金 最后更改时间 : 2016年12月22日 下午3:00:53
*/
private List<StationAndBaseLines> getStationWithRouteInfo(String cityCode, List<BaseStation> stations) {
List<StationAndBaseLines> stationAndBaseLinesList = new ArrayList<>();
// 在站点信息中加入线路及实时车辆信息
stations.forEach(station -> {
if (station.getStationid() != null && cityCode != null) {
List<BaseRoute> baseRoutes = baseRouteService.getRoutesByStationId(station.getStationid().toString(),
cityCode, TimeUtils.decideSeason());
List<BaseLine> lines = new ArrayList<>();// 线路信息
// 得到实时车辆信息
baseRoutes.forEach(baseRoute -> {
RouteInBaseLine routeInBaseLine = new RouteInBaseLine();
BeanUtils.copyProperties(baseRoute, routeInBaseLine);
RealTime busRealTimeInfo = getBusDetailInfo(cityCode, station, baseRoute);
lines.add(new BaseLine(routeInBaseLine, busRealTimeInfo));
});
// 构建站点及线路信息对象
StationAndBaseLines stationAndBaseLines = new StationAndBaseLines(station, lines);
stationAndBaseLinesList.add(stationAndBaseLines);
}
});
// 若要去重则调用travelService.duplicateStations(stationAndRoutesList)即可,这边不做处理,一期是因为数据问题
return stationAndBaseLinesList;
}
/**
* 功能描述:获取默认范围内的附近站点信息 作者:温海金 最后更改时间 : 2016年12月22日 下午3:00:53
*/
private RealTime getBusDetailInfo(String cityCode, BaseStation station, BaseRoute baseRoute) {
return travelServiceNew.getNearestBus(cityCode, station, baseRoute, null);
}
/**
* 功能描述:获取默认范围内的附近站点信息 (原 附近站点QueryController.java 中的nearStations接口) 作者:温海金
* 最后更改时间 : 2016年12月22日 下午3:00:53
*/
@Override
public NearStationsWithLine nearStations(BaseStation baseStation) {
// 1.获取默认范围内的附近站点信息,按距离从近到远排序
List<BaseStation> stationsWithDefaltDistance = baseStationMapper.getNearStations(baseStation,
SysGlobalConstants.DEFAULT_DISTANCE);
// 2.纠偏处理
updataTheCorrectOfGps(stationsWithDefaltDistance);
List<StationAndBaseLines> StationAndBaseLinesList = getStationWithRouteInfo(baseStation.getCitycode(),
stationsWithDefaltDistance);
return new NearStationsWithLine(StationAndBaseLinesList);
}
/**
* 功能描述:为单个站点进行GPS纠偏处理 作者:温海金 最后更改时间 : 2016年12月22日 下午3:58:32
*/
@Override
public void updataTheCorrectOfGps(BaseStation station) {
if (station == null)
return;
double[] latlng = new double[2];
GpsCorrectUtil.transform(station.getLatitude().doubleValue(), station.getLongitude().doubleValue(), latlng);
station.setLatitude(BigDecimal.valueOf(latlng[0]));
station.setLongitude(BigDecimal.valueOf(latlng[1]));
}
/**
* 功能描述:为站点集合进行GPS纠偏处理 作者:温海金 最后更改时间 : 2016年12月22日 下午3:58:32
*/
@Override
public void updataTheCorrectOfGps(List<BaseStation> stations) {
stations.forEach(station -> {
updataTheCorrectOfGps(station);
});
}
/**
* <p>
* Title: getRoutesByStationId
* </p>
* <p>
* Description: 根据stationId获取所有经过该站点的线路
* </p>
*
* @author liuhao
*/
@Override
public List<BaseLine> getRoutesByStationId(String stationId, String cityCode) {
BaseStation station = getStationById(stationId, cityCode);
// 为每一个站点的经纬度做GPS矫正
this.updataTheCorrectOfGps(station);
List<BaseRoute> baseRoutes = baseRouteService.getRoutesByStationId(stationId, cityCode,
TimeUtils.decideSeason());
List<BaseLine> list = new ArrayList<>();
if (CollectionUtils.isEmpty(baseRoutes)) {
baseRoutes = new ArrayList<>();
}
baseRoutes.forEach(r -> {
RealTime bd = travelServiceNew.getNearestBus(cityCode, station, r,
travelServiceNew.getUserStationNo(r.getRouteid(), station, r.getDirection()));
list.add(new BaseLine(new RouteInBaseLine(r), bd == null ? new RealTime() : bd));
});
return list;
}
/**
* <p>
* Title: getRoutesByStationIdAndStationName
* </p>
* <p>
* Description: 根据当前stationId/stationName/cityCode获取到达目标站点所有线路集合
* </p>
*
* @author liuhao
*/
@Override
public List<BaseLine> getRoutesByStationIdAndStationName(String stationId, String stationName, String cityCode) {
List<RouteInBaseLine> routeInBaseLines = baseRouteService.queryRoutesByStationIdAndStationName(stationId,
stationName, cityCode, TimeUtils.decideSeason());
BaseStation userStation = baseStationMapper.getStationById(stationId, cityCode);
List<BaseLine> baseLines = new ArrayList<>();
if (!CollectionUtils.isEmpty(routeInBaseLines)) {
routeInBaseLines.forEach(routeInBaseLine -> {
BaseLine baseLine = new BaseLine();
baseLine.setRouteInBaseLine(routeInBaseLine);
BaseRoute baseRoute = new BaseRoute();
BeanUtils.copyProperties(routeInBaseLine, baseRoute);
RealTime realTime = travelServiceNew.getNearestBus(cityCode, userStation, baseRoute, travelServiceNew
.getUserStationNo(routeInBaseLine.getRouteid(), userStation, routeInBaseLine.getDirection()));
baseLine.setRealTime(realTime);
baseLines.add(baseLine);
});
}
return baseLines;
}
/**
* 获取城市所有站点
*
* @auther yangyang
* @param cityCode
* @return
*/
@Override
public Map<String, BaseStation> getCityStations(String cityCode, String routeId, int direction) {
List<BaseStation> stationList = baseStationMapper.getCityStations(cityCode, routeId, direction);
if (StringUtils.isEmpty(stationList)) {
return Collections.emptyMap();
}
Map<String, BaseStation> map = new HashMap<>();
stationList.forEach(station -> {
map.put(String.valueOf(station.getStationid()), station);
});
return map;
}
@Override
public BaseStation queryStationByTicketIdAndStationNo(String ticketId, int direction, int onBusStationNo) {
return baseStationMapper.queryStationByTicketIdAndStationNo(ticketId, direction, onBusStationNo);
}
@Override
public List<RealTime> getRealTimeInfo(RealTimeQueryModel realTime) {
// 根据stationId获取到目标站点
BaseStation station = this.getStationByStationId(realTime.getStationid(), realTime.getCitycode());
// 为站点的经纬度做GPS矫正
this.updataTheCorrectOfGps(station);
List<RealTime> list = travelServiceNew.getBusList(realTime, station);
if (CollectionUtils.isEmpty(list)) {
list = Collections.emptyList();
}
Collections.sort(list, (a, b) -> { // 站序从小到大排序
if (a.getDesc().getStationnumber() == b.getDesc().getStationnumber()) {
return a.getDesc().getDistance().compareTo(b.getDesc().getDistance());
}
return a.getDesc().getStationnumber() - b.getDesc().getStationnumber();
});
baseRouteService.correctBusLonAndLan(list, baseRouteService.processMapPath(realTime.getRouteid(),
realTime.getDirection(), realTime.getCitycode()));
return list;
}
@Override
public List<BaseStation> getAllStations() {
return baseStationMapper.getAllStations();
}
@Override
public List<BaseStation> queryStationsByStationIdsAndCityCodes(List<BaseStationQueryModel> model) {
return baseStationMapper.queryStationsByStationIdsAndCityCodes(model);
}
}