springboot整合redis实战

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);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值