Springcloud整合redis,实现天气数据的缓存存取

本文介绍如何在Spring Boot项目中整合Redis,通过配置pom.xml和application.yml,实现天气数据的缓存与更新。利用RedisTemplateBean进行序列化设置,减少第三方API调用,提高查询效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom.xml引入

<!-- 整合redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>${spring.cloud.version}</version>
        </dependency> 

application.yml 

#Redis数据库索引(默认为0)
#Redis服务器地址
#Redis服务器连接端口
#Redis服务器连接密码(默认为空)
#连接池最大连接数(使用负值表示没有限制)
#连接池最大阻塞等待时间(使用负值表示没有限制)
#连接池中的最大空闲连接 
#连接池中的最小空闲连接
#连接超时时间(毫秒)
spring:
  application:
    name: weather
  redis:
    database: 0
    host: 120.22.0.142
    port: 6379
    password: 12322456
    pool:
      max-active: 200
      max-wait: -1
      max-idle: 10
      min-idle: 0
    timeout: 1000 

配置RedisTemplate Bean 

package com.example.config;

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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 我们可以每半个小时,去拉取下第三方的天气数据,缓存在redis,每半个小时更新。
 * 这样不仅可以减少第三方api的接口压力,也可以提高我们的查询速度,毕竟很多第三方免费 查询接口,都是有次数限制的,经常查询,次数太多了,就用不了了。
 * @author Administrator
 */
@Configuration
public class RedisConfig {

    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();

        template.setConnectionFactory(factory);

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

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);

        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;

    }

}
业务代码

首先从缓存中判断是否存在key,这里的key指的就是我们获取天气数据的uri。如果不存在这个key,说明没有从这个uri获取数据,就要去请求uri,取得数据,并存入缓存,下次请求,直接从缓存中取。 

@Service
public class WeatherServiceImpl implements WeatherService{

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    
    String uri = "http://wthrcdn.etouch.cn/weather_mini?city=深圳";

    @Override
    public WeatherData getWeather() {
        
        String body = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //key就是uri,如果redis有这个key,就从缓存中获取,没有的话,就去请求
        if(stringRedisTemplate.hasKey(uri)){
            //redis缓存数据
            body = ops.get(uri);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                WeatherData data = objectMapper.readValue(body, WeatherData.class);
                return data;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            //如果缓存中没有,需要取出数据,并存入缓存
            ResponseEntity<String> weatherData = restTemplate.getForEntity(uri, String.class);
            //使用ObjectMapper进行处理
            ObjectMapper mapper = new ObjectMapper();
            if(weatherData.getStatusCodeValue() == 200){
                body = weatherData.getBody();
                WeatherData weatherData2 = null;
                try {
                    weatherData2 = mapper.readValue(body, WeatherData.class);
                    ops.set(uri, body, 5*60*1000);
                } catch (Exception e) {
                    e.printStackTrace();
                } 
                return weatherData2;
            }
        }
        return null;
    }
}
运行请求接口,我这边的接口是http://localhost:8764/weather/getCityWeather

可以看到数据,已经存储进来了,key是对应的uri, xshell客户端访问redis的key,我们可以发现,数据已经存储成功

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值