springboot配置redis+jedis,支持基礎redis,並實現jedis GEO地圖功能

Springboot配置redis+jedis,已在項目中測試併成功運行,支持基礎redis操做,並經過jedis作了redis GEO地圖的java實現,GEO支持存儲地理位置信息來實現諸如附近的人、搖一搖等這類依賴於地理位置信息的功能。本文參考了網上多篇博文,具體的記錄不記得了...因此不一一列出,有任何問題請聯繫我刪除。html

1、添加依賴

<!--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>

2、配置文件(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

3、初始化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;
    }
}

4、封裝jedis經常使用方法

我主要封裝了關於GEO地圖的方法,實際項目中只用了其中兩個功能,因此我只寫了兩個,要用其餘的本身去封裝就行了。java

@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;
    }
}

5、實際使用

@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;
    }

}
相關文章
相關標籤/搜索