Springboot配置redis+jedis,已在项目中测试并成功运行,支持基础redis操作,并通过jedis做了redis GEO地图的java实现,GEO支持存储地理位置信息来实现诸如附近的人、摇一摇等这类依赖于地理位置信息的功能。本文参考了网上多篇博文,具体的记录不记得了...所以不一一列出,有任何问题请联系我删除。
一、添加依赖
- <!--redis-->
- <!-- 注意:1.5版本的依赖和2.0的依赖不一样,1.5名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar -->
- <exclusions>
- <exclusion>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- </exclusion>
- <exclusion>
- <groupId>io.lettuce</groupId>
- <artifactId>lettuce-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <!-- 添加jedis客户端 -->
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- </dependency>
- <!--spring2.0集成redis所需common-pool2-->
- <!-- 必须加上,jedis依赖此 -->
- <!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/-->
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-pool2</artifactId>
- <version>2.5.0</version>
- </dependency>
- <!-- 将作为Redis对象序列化器 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.47</version>
- </dependency>
二、配置文件(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<String, Object> 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<String, Object> 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<GeoRadiusResponse> 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<String> 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<BgUser> 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<BgUser> getNearUser(int distance, BgUser bgUser) {
- List<BgUser> bgUsers = new ArrayList<>();
- if (bgUser.getLongitude() == null || bgUser.getLatitude() == null) {
- return bgUsers;
- }
- GeoCoordinate geoCoordinate = new GeoCoordinate(bgUser.getLongitude(), bgUser.getLatitude());
- List<GeoRadiusResponse> geoRadiusResponses = jedisClient.geoRadius(key, geoCoordinate, distance, GeoUnit.M);
- //这里是java8流式编程,这样用很方便
- List<Long> 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;
- }
-
- }