【redis】SpringBoot整合+geo地理位置应用

Jedis和lettuce区别:

·Jedis:

直接连接的Redis Server,如果在多线程环境下是非线程安全的。每个线程都去拿自己的 Jedis 实例,当连接数量增多时,资源消耗阶梯式增大,连接成本就较高了。

解决安全的问题,可以用线程池。

·lettuce:

基于Netty的,Netty 是一个多线程、事件驱动的 I/O 框架。连接实例可以在多个线程间共享,当多线程使用同一连接实例时,是线程安全的。

所以,一个多线程的应用可以使用同一个连接实例,而不用担心并发线程的数量。当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

通过异步的方式可以让我们更好的利用系统资源,而不用浪费线程等待网络或磁盘I/O。所以 Lettuce 可以帮助我们充分利用异步的优势。

整合步骤:

1.pom

        <!--springboot的redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.配置

配置文件:

server:
  port: 5555
spring:
  redis:
    database: 1
    host: 127.0.0.1
    port: 6379
#    password:     #用的本地的redis数据库 所以不用密码
    lettuce:
      pool:
        max-active: 8   #连接池最大连接数(使用负值表示没有限制)
        max-idle: 5     #连接池中的最大空闲连接
        min-idle: 0     #连接池中的最小空闲连接
        max-wait: -1    #连接池最大阻塞等待时间(使用负值表示没有限制)
    timeout: 10000ms    #连接超时时间(毫秒)

fbe13c5424723ee6338609af2537336f.png

做成service或者util都可以

RedisConfig:

package com.example.redistest.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author lie
 * @Description
 */
@Configuration
public class RedisConfig {

    @Value("${spring.redis.database}")
    private int database;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
//    @Value("${spring.redis.password}")  //因为连接的是本地redis,没设置密码,所以不用
//    private String password;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setDatabase(database);
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
//        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));

        LettuceClientConfiguration.LettuceClientConfigurationBuilder lettuceClientConfigurationBuilder = LettuceClientConfiguration.builder();
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration,
                lettuceClientConfigurationBuilder.build());
        return lettuceConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        //---------转换json--start-------//
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //--------转换json--end-----//
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

RedisTemplate:(基本类型+geo)

package com.example.redistest.service.impl;


import com.example.redistest.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis操作实现类
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public Long del(List<String> keys) {
        return redisTemplate.delete(keys);
    }

    @Override
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    @Override
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    @Override
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    @Override
    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    @Override
    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    @Override
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public List<Object> hVals(String key) {
        return redisTemplate.opsForHash().values(key);
    }

    @Override
    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    @Override
    public void hSetAll(String key, Map<String, ?> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    @Override
    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    @Override
    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    @Override
    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    @Override
    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    @Override
    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

//    @Override
//    public Long sAdd(String key, Object... values) {
//        return redisTemplate.opsForSet().add(key, values);
//    }

    @Override
    public Long sAdd(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    @Override
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    @Override
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    @Override
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    @Override
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    @Override
    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    @Override
    public Long lPush(String key, Object value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }

    @Override
    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    @Override
    public Long lPushAll(String key, Long time, Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }

    @Override
    public Set<String> keys() {
         return this.redisTemplate.keys("*");
    }

    /**
     * 添加一个元素, zset与set最大的区别就是每个元素都有一个score,因此有个排序的辅助功能;  zadd
     *
     * @param key
     * @param value
     * @param score
     */
    @Override
    public void zadd(String key, Object value, double score) {
        redisTemplate.opsForZSet().add(key, value, score);
    }

    /**
     * 删除元素 zrem
     * @param key
     * @param value
     */
    @Override
    public void zdel(String key, Object value) {
        redisTemplate.opsForZSet().remove(key, value);
    }

    /**
     * score的增加or减少 zincrby
     * @param key
     * @param value
     * @param score
     */
    @Override
    public Double incrScore(String key, Object value, double score) {
        return redisTemplate.opsForZSet().incrementScore(key, value, score);
    }

    /**
     * 查询集合中指定顺序的值和score,0, -1 表示获取全部的集合内容
     * @param key
     * @param start
     * @param end
     * @return
     */
    @Override
    public Set<ZSetOperations.TypedTuple<Object>> rangeWithScore(String key, long start, long end) {
        return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
    }

    /**
     * 获取对象个数
     * @param key
     * @return
     */
    @Override
    public Object hLen(String key) {
        return redisTemplate.opsForHash().size(key);
    }
}
package com.example.redistest.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @Author lie
 * @Description
 */
@Component
public class GeoHashUtil {

    @Autowired(required = false)
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 添加节点及位置信息
     * @param geoKey 位置集合
     * @param pointName 位置点标识
     * @param longitude 经度
     * @param latitude 纬度
     */
    public Long geoAdd(String geoKey, double longitude, double latitude, String pointName){
        Point point = new Point(longitude, latitude);
        return redisTemplate.opsForGeo().add(geoKey, point, pointName);
    }

    /**
     * 以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离
     * @param geoKey    key
     * @param longitude 经度
     * @param latitude 维度
     * @param radius    距离
     * @param metricUnit 距离单位,例如 Metrics.KILOMETERS
     * @param limit 人数
     */
    public List<GeoResult<RedisGeoCommands.GeoLocation<String>>> findRadius(String geoKey
            , double longitude, double latitude, double radius, Metrics metricUnit, int limit){
        // 设置检索范围
        Point point = new Point(longitude, latitude);
        Circle circle = new Circle(point, new Distance(radius, metricUnit));
        // 定义返回结果参数,如果不指定默认只返回content即保存的member信息
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs().includeDistance().includeCoordinates()
                .sortAscending()
                .limit(limit);
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius(geoKey, circle, args);
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        return list;
    }

    /**
     * 计算指定key下两个成员点之间的距离
     * @param geoKey  key
     * @param member1 位置1
     * @param member2 位置2
     * @param unit 单位
     */
    public Distance calDistance(String geoKey, String member1, String member2
            , RedisGeoCommands.DistanceUnit unit){
        Distance distance = redisTemplate.opsForGeo()
                .distance(geoKey, member1, member2, unit);
        return distance;
    }

    /**
     * 根据成员点名称查询位置信息
     * @param geoKey geo key
     * @param members 名称数组
     */
    public List<Point> geoPosition(String geoKey, String[] members){
        List<Point> points = redisTemplate.opsForGeo().position(geoKey, members);
        return points;
    }

    /**
     * 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
     * @param key redis的key
     * @param name 名称
     * @param distance 距离
     * @param count 人数
     */
    public GeoResults<RedisGeoCommands.GeoLocation<String>> geoNearByPlace(String key, String name, Integer distance, Integer count) {
        //params: 距离量, 距离单位
        Distance distances = new Distance(distance, Metrics.KILOMETERS);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(count);
        //params: key, 地方名称, Circle, GeoRadiusCommandArgs
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius(key, name, distances, args);
        return results;
    }


    /**
     * 返回一个或多个位置元素的 Geohash 表示
     * @param key redis的key
     * @param members  名称的数组
     */
    public List<String> geoHash(String key, String[] members) {
        //params: key, 地方名称...
        List<String> results = redisTemplate.opsForGeo().hash(key, members);
        return results;
    }
}

3.引入工具类或者service调用方法使用即可(下面做的例子)

impl:

package com.example.redistest.test.service.impl;

import com.example.redistest.service.RedisService;
import com.example.redistest.test.service.StockService;
import com.example.redistest.util.GeoHashUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author lie
 * @Description
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {

    @Autowired(required = false)
    private RedisService redisService;

    @Autowired
    private GeoHashUtil geoHashUtil;

    /**
     * 加库存
     * @param stockNum
     * @return
     */
    @Override
    public String addStock(Integer stockNum) {
        Long decr = redisService.incr("stock:37", stockNum);
        log.info(String.valueOf(decr));
        return redisService.get("stock:37").toString();
    }

    /**
     * 减库存
     * @param stockNum
     * @return
     */
    @Override
    public String subtractStock(Integer stockNum) {
        Long decr = redisService.decr("stock:37", stockNum);
        log.info(String.valueOf(decr));
        return redisService.get("stock:37").toString();
    }

    /**
     * 将指定的地理空间位置(纬度、经度、名称)添加到指定的key中。
     * @param key redis的key
     * @param longitude   经度
     * @param latitude   纬度
     * @param name  名称
     */
    @Override
    public Long addGeo(String key, double longitude, double latitude, String name) {
        return geoHashUtil.geoAdd(key,longitude,latitude,name);
    }

    /**
     * 从key里返回所有给定位置元素的位置(经度和纬度)。
     * @param key redis的key
     * @param nameList  geo位置成员的名字,可以是多个,用逗号分割
     */
    @Override
    public List<Point> queryGeo(String key, String nameList) {
        String[] split = nameList.split(",");
//        List<String> cityNames = new ArrayList<>(Arrays.asList(split));
        List<Point> points = geoHashUtil.geoPosition(key, split);
        return points;
    }

    /**
     * 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
     * @param key   key
     * @param pointName 中心地点名
     * @param distance  距离
     * @param count     数量
     */
    @Override
    public GeoResults<RedisGeoCommands.GeoLocation<String>> locationInfo(String key,String pointName, Integer distance, Integer count) {
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = geoHashUtil.geoNearByPlace(key, pointName, distance, count);
        return geoResults;
    }


}

controller:

package com.example.redistest.test.controller;

import com.example.redistest.test.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author lie
 * @Description 测试redis
 */
@RestController
@RequestMapping("RedisTestController")
public class RedisTestController {

    @Autowired
    private StockService stockService;
    /**
     * 增加库存
     * @param stockNum
     * @return 增加后的库存
     */
    @GetMapping("addStock")
    public String addStock(Integer stockNum){
        return stockService.addStock(stockNum);
    }

    /**
     * 减少库存
     * @param stockNum
     * @return 增加后的库存
     */
    @GetMapping("subtractStock")
    public String subtractStock(Integer stockNum){
        return stockService.subtractStock(stockNum);
    }

    /**
     * 将指定的地理空间位置(纬度、经度、名称)添加到指定的key中。
     * @param key redis的key
     * @param longitude   经度
     * @param latitude   纬度
     * @param name  名称
     */
    @GetMapping("addGeo")
    public Long addGeo(String key, double longitude, double latitude, String name){
        return stockService.addGeo(key,longitude,latitude,name);
    }

    /**
     * 从key里返回所有给定位置元素的位置(经度和纬度)。
     * @param key redis的key
     * @param nameList  geo位置成员的名字,可以是多个,用逗号分割
     */
    @GetMapping("queryGeo")
    public List<Point> queryGeo(String key, String nameList){
        return stockService.queryGeo(key,nameList);
    }

    /**
     * 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
     * @param key   key
     * @param pointName 中心地点名
     * @param distance  距离
     * @param count     数量
     */
    @GetMapping("locationInfo")
    public GeoResults<RedisGeoCommands.GeoLocation<String>> locationInfo(String key, String pointName, Integer distance, Integer count){
        return stockService.locationInfo(key,pointName,distance,count);
    }

}

启动服务,看结果:

·库存增加1000(查看redis结果一致)

·库存减少200(查看redis结果一致)

·添加位置北京、上海、广州(查看redis结果一致)

·查看经纬度(多个地点)

·查看已北京为中心10000km以内的3个最近的地点,同时返回距离、经纬度、地点名称

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值