Springboot配置redis+jedis,已在项目中测试并成功运行,支持基础redis操作,并通过jedis做了redis GEO地图的java实现,GEO支持存储地理位置信息来实现诸如附近的人、摇一摇等这类依赖于地理位置信息的功能。本文参考了网上多篇博文,具体的记录不记得了...所以不一一列出,有任何问题请联系我删除。
一、添加依赖
org.springframework.boot
spring-boot-starter-data-redis
redis.clients
jedis
io.lettuce
lettuce-core
redis.clients
jedis
org.apache.commons
commons-pool2
2.5.0
com.alibaba
fastjson
1.2.47
二、配置文件(application.properties)
#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=12345
spring.redis.timeout=20000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=100
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
#寻找队伍,主键key
join.team.key=joinTeam
#寻找队伍,失效时间(单位:秒)
join.team.time=1800
三、初始化redis和jedis
@Slf4j
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
/**
* 生成key的策略
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
//设置自动key的生成规则,配置springboot的注解,进行方法级别的缓存
//使用:进行分割,可以更多的显示出层级关系
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getName());
stringBuilder.append(":");
stringBuilder.append(method.getName());
for (Object object : objects) {
stringBuilder.append(":" + String.valueOf(object));
}
String key = String.valueOf(stringBuilder);
log.info("自动生成Redis Key -> [{}]", key);
return key;
}
};
}
@Bean
@Override
public CacheManager cacheManager() {
//初始化缓存管理器,在这里可以缓存的整体过期时间等,默认么有配置
log.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory);
return builder.build();
}
@Bean
public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
//设置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//配置redisTemplate
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
RedisSerializer serializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(serializer);//key序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);//value序列化
redisTemplate.setHashKeySerializer(serializer);//Hash key 序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);//Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Override
@Bean
public CacheErrorHandler errorHandler() {
//异常处理,当Redis发生异常时,打印日志,但是程序正常运行
log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
log.error("Redis occur handleCacheGetError:key -> [{}]", o, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
log.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", o, o1, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
log.error("Redis occur handleCacheEvictError:key -> [{}]", o, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error("Redis occur handleCacheClearError:", e);
}
};
return cacheErrorHandler;
}
@Bean
public JedisPoolConfig setJedisPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);//最大连接数,连接全部用完,进行等待
poolConfig.setMinIdle(minIdle); //最小空余数
poolConfig.setMaxIdle(maxIdle); //最大空余数
return poolConfig;
}
@Bean
public JedisPool setJedisPool(JedisPoolConfig jedisPoolConfig) {
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
return jedisPool;
}
}
四、封装jedis常用方法
我主要封装了关于GEO地图的方法,实际项目中只用了其中两个功能,所以我只写了两个,要用其他的自己去封装就好了。
@Slf4j
@Component
public class JedisClient {
@Autowired
private JedisPool jedisPool;
@Value("${spring.redis.password}")
private String password;
@Value("${join.team.key}")
private String key;
@Value("${join.team.time}")
private String time;
public void release(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
private Jedis getJedis(JedisPool jedisPool) {
Jedis jedis = jedisPool.getResource();
jedis.auth(password);
//设置键为key时的超时时间(寻找队伍,失效时间)
jedis.expire(key, Integer.parseInt(time));
return jedis;
}
/**
* 增加用户地理位置的坐标
* @param key
* @param coordinate
* @param memberName
* @return
*/
public Long geoadd(String key, GeoCoordinate coordinate, String memberName) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.geoadd(key, coordinate.getLongitude(), coordinate.getLatitude(), memberName);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
/**
* 根据给定地理位置坐标获取指定范围的用户地理位置集合(匹配位置的经纬度 + 相隔距离 + 从近到远排序)
* @param key
* @param coordinate
* @param radius 指定半径
* @param geoUnit 单位
* @return
*/
public List geoRadius(String key, GeoCoordinate coordinate, int radius, GeoUnit geoUnit) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.georadius(key, coordinate.getLongitude(), coordinate.getLatitude(), radius, geoUnit);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
/**
* 查询两位置距离
* @param key
* @param member1
* @param member2
* @param unit
* @return
*/
public Double geoDist(String key, String member1, String member2, GeoUnit unit) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.geodist(key, member1, member2, unit);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
/**
* 从集合中删除元素
* @param key
* @param member
* @return
*/
public Boolean geoRemove(String key, String member) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.zrem(key, member) == 1 ? true : false;
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
/**
* 加入到sort里的数量
* @param key
* @return
*/
public Long geoLen(String key) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.zcard(key);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
/**
* 所有集合
* @param key
* @return
*/
public List geoMembers(String key) {
Jedis jedis = null;
try {
jedis = this.getJedis(jedisPool);
return jedis.sort(key);
} catch (Exception e) {
log.error(e.getMessage());
} finally {
release(jedis);
}
return null;
}
}
五、实际使用
@Service
@Transactional
public class BgUserServiceImpl extends AbstractService implements BgUserService {
@Resource
private BgUserMapper bgUserMapper;
@Resource
private BgUserRoleService bgUserRoleService;
@Resource
private BgUserGameService bgUserGameService;
@Autowired
private JedisClient jedisClient;
@Value("${join.team.key}")
private String key;
...
@Override
public int joinTeam(BgUser bgUser) {
if (bgUser.getLongitude() == null || bgUser.getLatitude() == null) {
return 0;
}
GeoCoordinate geoCoordinate = new GeoCoordinate(bgUser.getLongitude(), bgUser.getLatitude());
long count = jedisClient.geoadd(key, geoCoordinate, bgUser.getUserId().toString());
return (int)count;
}
@Override
public List getNearUser(int distance, BgUser bgUser) {
List bgUsers = new ArrayList<>();
if (bgUser.getLongitude() == null || bgUser.getLatitude() == null) {
return bgUsers;
}
GeoCoordinate geoCoordinate = new GeoCoordinate(bgUser.getLongitude(), bgUser.getLatitude());
List geoRadiusResponses = jedisClient.geoRadius(key, geoCoordinate, distance, GeoUnit.M);
//这里是java8流式编程,这样用很方便
List userIds = geoRadiusResponses.stream().map(GeoRadiusResponse::getMemberByString).map(geoRadiusResponse -> Long.valueOf(geoRadiusResponse)).collect(Collectors.toList());
if (userIds != null && userIds.size() > 0) {
bgUsers = bgUserMapper.getListByUserIds(userIds);
}
return bgUsers;
}
}