redis入门的简单使用
在实习过程因为公司要求使用redis来解决问题,于是我就用了一个上午的时间,速成了一些redis的基本使用,也简单的记录一下
1.找到官网
根据安装地址来进行下载,Window 下安装
**下载地址:**https://github.com/dmajkic/redis/downloads。
下载到的Redis支持32bit和64bit。根据自己实际情况选择,将64bit的内容cp到自定义盘符安装目录取名redis。 如 C:\reids
打开一个cmd窗口 使用cd命令切换目录到 C:\redis 运行 redis-server.exe redis.conf 。
如果想方便的话,可以把redis的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个redis.conf可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:
这时候另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了。
切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。
设置键值对 set myKey abc
取出键值对 get myKey
2.springboot使用redis
1.导入maven包
<!--redis jar包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
2.配置redis的连接信息
#访问地址
redis.host=127.0.0.1
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留
redis.password=
#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制
redis.maxActive=600
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true
3.redis相关bean的配置
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* Redis 相关的Bean配置
@@ -13,6 +24,26 @@
public class RedisConfig {
/**
* 选择redis作为默认缓存工具
* @param redisConnectionFactory
* @return
*/
/*@Bean
//springboot 1.xx
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
return rcm;
}*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
@@ -29,4 +60,61 @@
template.afterPropertiesSet();
return template;
}
/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
4.entiy实体类配置
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Author by lbWang
* @Date 2021/10/31 18:06
*/
@Data
public class MapOnLeft {
@AllArgsConstructor
@NoArgsConstructor
public class MapOnLeft implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;//
private String center;//经纬度中心点
private String type;//SITE 工地;COMPANY 公司;DOCK 中转码头 ;DISCHARGE 消纳场
private String status;//状态 UN_START_WORK 未生效 VALID 有效
}
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Author by lbWang
* @Date 2021/10/31 17:02
*/
@Data
public class MapOnRight {
@AllArgsConstructor
@NoArgsConstructor
public class MapOnRight implements Serializable {
private static final long serialVersionUID = 1L;
private Integer siteNum;//工地数量
private Integer siteTotalExcavation;//总出土量
private String companyNum;//运输公司
@@ -15,4 +24,5 @@
private Integer dischargeNum;//消纳场数
private Integer remainCapacity;//剩余容量
private String dockNum;//中转码头
}
5.service层中将接口数据存到redis中
import hangzhou.cgw.zhzts.common.dto.zhztc.*;
import hangzhou.cgw.zhzts.common.dto.zhztc.query.LatitudeAndLongitudeReq;
import hangzhou.cgw.zhzts.common.dto.zhztc.query.PlaceDistanceReq;
import hangzhou.cgw.zhzts.common.manager.remote.ZhztcBaseClient;
import hangzhou.cgw.zhzts.common.utils.JsonUtil;
import hangzhou.cgw.zhzts.common.utils.PageResult;
import hangzhou.cgw.zhzts.common.utils.RedisUtil;
import hangzhou.cgw.zhzts.common.utils.Result;
import hangzhou.cgw.zhzts.trad.dto.statistics.*;
import hangzhou.cgw.zhzts.trad.manager.LoadMktSiteDischargeCompanyManager;
import hangzhou.cgw.zhzts.trad.mapper.statistics.HomeStatisticsMapper;
import hangzhou.cgw.zhzts.trad.service.ZhztcAbstractService;
import hangzhou.cgw.zhzts.trad.util.SerializeUtil;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
@Slf4j
@@ -28,6 +36,10 @@
@Autowired
private LoadMktSiteDischargeCompanyManager loadMktSiteDischargeCompanyManager;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisUtil redisUtil;
@Autowired
public HomeStatisticsService(ZhztcBaseClient zhztcBaseClient) {
super(zhztcBaseClient);
}
@@ -73,17 +85,44 @@
* @return
*/
public Result<MapOnRight> queryMapOnRight(){
ZhztcResult<MapOnRight> result = this.zhztcFeignMuckClient.selectMapOnRight();
return ZhztcResult.convertResult(result);
//1.判断redis中对应的key有没有值
String key = "mapOnRightDatumList";
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey){
MapOnRight mapOnRight= (MapOnRight) redisUtil.get(key);
return ZhztcResult.convertResult(ZhztcResult.success(mapOnRight));
}else {
ZhztcResult<MapOnRight> result = this.zhztcFeignMuckClient.selectMapOnRight();
MapOnRight mapOnRightdata = result.getData();
boolean set = redisUtil.set(key,mapOnRightdata);
MapOnRight mapOnRight = (MapOnRight) redisUtil.get(key);
return ZhztcResult.convertResult(ZhztcResult.success(mapOnRight));
}
}
/**
* 地图左侧信息
* @return
*/
public Result<List<MapOnLeft>> queryMapOnLeft(){
ZhztcResult<List<MapOnLeft>> listZhztcResult = this.zhztcFeignMuckClient.selectMapOnLeft();
return ZhztcResult.convertResult(listZhztcResult);
//1.判断redis中对应的key有没有值
String key = "listZhztcResult";
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey){
List mapOnLeftList = redisTemplate.opsForList().range("listZhztcResult", 0, -1);
System.out.println(mapOnLeftList);
return ZhztcResult.convertResult(ZhztcResult.success(mapOnLeftList));
}else {
ZhztcResult<List<MapOnLeft>> listZhztcResult = this.zhztcFeignMuckClient.selectMapOnLeft();
List<MapOnLeft> listZhztcResultData = listZhztcResult.getData();
//boolean set = redisUtil.set(key,mapOnRightdata);
for (MapOnLeft listZhztcResultDatum : listZhztcResultData) {
//把每一个goods对象保存到redis中的List中。
redisTemplate.opsForList().rightPush(key, listZhztcResultDatum);
}
List mapOnLeftList = redisTemplate.opsForList().range("listZhztcResult", 0, -1);
System.out.println(mapOnLeftList);
return ZhztcResult.convertResult(ZhztcResult.success(mapOnLeftList));
}
}
/**
* 推荐信息
* @param placeDistanceReq
* @return
*/
public PageResult<PlaceDistance> queryPlaceDistanceList(PlaceDistanceReq placeDistanceReq){
ZhztcPageResult<PlaceDistance> listZhztcPageResult = this.zhztcFeignMuckClient.selectPlaceDistanceList(placeDistanceReq);
return ZhztcPageResult.convertPageResult(listZhztcPageResult);
}
}
6.对象序列化工具类
package hangzhou.cgw.zhzts.trad.util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return null;
}
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return null;
}
/**
* 序列化 list 集合
*
* @param list
* @return
*/
public static byte[] serializeList(List<?> list) {
if (list == null || list.size() <= 0) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
for (Object obj : list) {
oos.writeObject(obj);
}
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(oos);
close(baos);
}
return bytes;
}
/**
* 反序列化 list 集合
*
* @param
* @return
*/
public static List<?> unserializeList(byte[] bytes) {
if (bytes == null) {
return null;
}
List<Object> list = new ArrayList<Object>();
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
while (bais.available() > 0) {
Object obj = (Object) ois.readObject();
if (obj == null) {
break;
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(bais);
close(ois);
}
return list;
}
/**
* 关闭io流对象
*
* @param closeable
*/
public static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
7.该模块所对应的redis缓存配置文件
###################以下为mybatis-plus的常规配置###########################
# 设置mybatis输出SQL日志到控制台
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
###################???redis????###########################
##????????????????????
spring.redis.jedis.pool.max-active=10000
##???????????????????????
spring.redis.jedis.pool.max-wait=-1
##???????????
spring.redis.jedis.pool.max-idle=10000
## ???????????
spring.redis.jedis.pool.min-idle=0
## ???? ???
spring.redis.timeout=1800000
3.本地启动redis
1.使用cd命令切换目录到 D:\redis 运行 redis-server.exe
2.启动成功后另启一个cmd窗口,原来的不要关闭,不然就无法访问服务端了
3.切换到redis目录下运行 redis-cli.exe -h 127.0.0.1 -p 6379 。
设置键值对 set myKey abc
取出键值对 get myKey
启动完毕。
redis服务停用 redis-cli shutdown