SpringBoot 天气预报系统 添加Redis缓存(2)

由于我们的天气预报系统采用的是第三方的服务  所以可能出现以下几个问题:

    1)用户调用我们的接口  响应的时间过长

    2)可能有调用次数的限制

    3)并发访问量时  不能很好地处理或者给第三方带来过大的压力

解决方法:添加Redis缓存  redis时key-value的键值存储方式 读取速度很快 可以使用缓存来解决问题

                   及时响应,减少服务调用的次数。

实现:

需要redis 3.2.100  以及添加依赖;

compile("org.springframework.boot:spring-boot-starter-data-redis")

下载windows redis3.2.100 

下载目录:windows版:https://github.com/MSOpenTech/redis/releases

解压到本地目录

cmd ---->切换到解压目录---->redis-server.exe redis.windows.conf   启动redis服务


修改Service类:

 /**
     * 根据传入的url返回WeatherResponse对象
     *
     * @param url
     * @return
     */
    private WeatherResponse getDataByUrl(String url) {
        //将url作为key
        String key = url;
        String responseBody = null;

        ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
        //在redis中是否存在缓存  如有查缓存  若没有用服务
        if(stringRedisTemplate.hasKey(key)){
            //有缓存
            logger.info("redis has data ,key={}",key);
            responseBody = ops.get(key);
        }else{
            //获取到url返回的内容  String类型
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            int statusCode = responseEntity.getStatusCodeValue();

            if(statusCode == 200){
                responseBody = responseEntity.getBody();
            }

            //写入缓存  30分钟过期
            logger.info("redis 添加缓存 ,key={}",key);
            ops.set(key,responseBody,TIME_OUT, TimeUnit.SECONDS);
        }

        //将json数据放到对象中
        ObjectMapper mapper = new ObjectMapper();
        WeatherResponse ws = null;
        try {
            ws = mapper.readValue(responseBody,WeatherResponse.class);
        } catch (IOException e) {
            //e.printStackTrace();
            logger.error("error!! e={}",e.getMessage());
        }
        return ws;
    }

浏览器访问:http://localhost:8080/weather/cityName/北京


没有配置redis的连接????没有配置redis的连接????没有配置redis的连接????没有配置redis的连接????

猜你喜欢

转载自blog.csdn.net/csdn_wangchen/article/details/79400675