·Jedis:
直接连接的Redis Server,如果在多线程环境下是非线程安全的。每个线程都去拿自己的 Jedis 实例,当连接数量增多时,资源消耗阶梯式增大,连接成本就较高了。
解决安全的问题,可以用线程池。
·lettuce:
基于Netty的,Netty 是一个多线程、事件驱动的 I/O 框架。连接实例可以在多个线程间共享,当多线程使用同一连接实例时,是线程安全的。
所以,一个多线程的应用可以使用同一个连接实例,而不用担心并发线程的数量。当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
通过异步的方式可以让我们更好的利用系统资源,而不用浪费线程等待网络或磁盘I/O。所以 Lettuce 可以帮助我们充分利用异步的优势。
org.springframework.boot spring-boot-starter-data-redis
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 #连接超时时间(毫秒)
做成service或者util都可以
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 redisTemplate() {
RedisTemplate 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;
}
}
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 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 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
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 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>> 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> results = redisTemplate.opsForGeo().radius(geoKey, circle, args);
List>> 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 geoPosition(String geoKey, String[] members){
List points = redisTemplate.opsForGeo().position(geoKey, members);
return points;
}
/**
* 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
* @param key redis的key
* @param name 名称
* @param distance 距离
* @param count 人数
*/
public GeoResults> 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> results = redisTemplate.opsForGeo().radius(key, name, distances, args);
return results;
}
/**
* 返回一个或多个位置元素的 Geohash 表示
* @param key redis的key
* @param members 名称的数组
*/
public List geoHash(String key, String[] members) {
//params: key, 地方名称...
List results = redisTemplate.opsForGeo().hash(key, members);
return results;
}
}
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 queryGeo(String key, String nameList) {
String[] split = nameList.split(",");
// List cityNames = new ArrayList<>(Arrays.asList(split));
List points = geoHashUtil.geoPosition(key, split);
return points;
}
/**
* 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
* @param key key
* @param pointName 中心地点名
* @param distance 距离
* @param count 数量
*/
@Override
public GeoResults> locationInfo(String key,String pointName, Integer distance, Integer count) {
GeoResults> geoResults = geoHashUtil.geoNearByPlace(key, pointName, distance, count);
return geoResults;
}
}
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 queryGeo(String key, String nameList){
return stockService.queryGeo(key,nameList);
}
/**
* 以给定的城市为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
* @param key key
* @param pointName 中心地点名
* @param distance 距离
* @param count 数量
*/
@GetMapping("locationInfo")
public GeoResults> locationInfo(String key, String pointName, Integer distance, Integer count){
return stockService.locationInfo(key,pointName,distance,count);
}
}
·库存增加1000(查看redis结果一致)
·库存减少200(查看redis结果一致)
·添加位置北京、上海、广州(查看redis结果一致)
·查看经纬度(多个地点)
·查看已北京为中心10000km以内的3个最近的地点,同时返回距离、经纬度、地点名称