1.引入redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.redis配置
package com.ocamar.mwms.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Bean
RedisTemplate<String,String> redisTemplate() {
RedisTemplate<String,String> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
/* value使用StringRedisSerializer序列化,默认是JDK序列化 */
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
}
3.编写redis操作工具类
package com.ocamar.mwms.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public void setExprire(String key, String value, Long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
}
4.向redis里面存入list对象
4-1.构造allLonLat对象
List<LongitudeLatitudeDTO> allLonLat = new ArrayList<>();
LongitudeLatitudeDTO obj = new LongitudeLatitudeDTO();
obj.setLatitude(23.3);
obj.setLongitude(34.3);
allLonLat.add(obj);
4-2.将list对象转换成json数组存入redis
redisUtil.set("allLonLat", JSON.toJSONString(allLonLat));
4.3 用到的类
@Data
public class LongitudeLatitudeDTO implements Serializable{
private Double Longitude;//经度
private Double Latitude;//纬度
}
4.从redis里面取出list对象
List<LongitudeLatitudeDTO> lonLat = JSON.parseArray(redisUtil.get("allLonLat").toString(), LongitudeLatitudeDTO.class);