访问服务器 request.getheader(origin)为null_10年老架构师,带你如何使用Redis提升应用的并发访问能力...

使用Redis提升应用的并发访问能力

有时,为了提升整个网站的性能,程序员会将经常需要访问的数据缓存起来,这样,在下次查缓存的使用与系统的时效性有着非常大的关系。当所使用的系统时效性要求不高时,选择使用本节将演示如何通过集成Redis服务器来进行数据的缓存,以提高微服务的并发访问能力。

为什么需要缓存

天气数据接口,本身时效性不是很高,而且又因为是Web服务,在调用过程中,本身是存在延时的。所以,采用缓存,一方面可以有效减轻访问天气接口服务带来的延时问题;另一方面也可以减轻天气接口的负担,提高并发访问量。

特别是使用第三方免费的天气API,这些API往往对用户的调用次数及频率有一定的限制。所以为了减轻天气API提供方的负荷,并不需要去实时调用其第三方接口。

在micro-weather-basic的基础上,程序员构建了一个micro-weather-redis项目作为示例

开发环境

为了演示本例,需要采用如下开发环境。

.JDK8。

.Gradle 4.0。

. Spring Boot Web Starter 2.0.0.M4。

Apache HttpClient 4.5.3。

.Spring Boot Data Redis Starter 2.0.0.M4。

.Redis 3.2.100。

f72593d38f179774d479acb530cc9f61.png

项目配置

Spring Boot Data Redis提供了Spring Boot对Redis的开箱即用功能。在原有的依赖基础上,添加Spring Boot Data Redis Starter的依赖。

/依赖关系dependencies{/l...//添加Spring Boot Data Redis Starter依赖compile('org.springframework.boot:spring-boot-starter-data-redis')//...}

下载、安装并运行Redis

在Linux平台上安装Redis比较简单,可以参考官方文档,详见https:lgithub.com/antirez/redis.

而在Windows平台,微软特别为Redis制作了安装包,下载地址为https:/lgithub.com/Micro-softArchive/redis/releases。本节所使用的案例,也是基于该安装包来进行的。双击redis-server.exe文件,就能快速启动Redis服务器了。

安装后,Redis默认运行在地址端口,如图6-2所示。

dc9dc1ae0c41f7956423cc7f464f6ce5.png

修改WeatherDataServicelmpl

修改WeatherDataServiceImpl,增加了StringRedisTemplate,用于操作Redis.

@servicepublic class WeatherDataServicelmpl implements WeatherDataService{  private final static Logger logger = Loggeractory.getLogger(WeatherDataServicempl.class);@Autowiredprivate RestTemplate restTemplate;@Autowiredprivate stringRedisTemplate stringRedisTemplate;private final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";private final Long TIME OUT = 1800L;//缓存超时时间                                                              overridepublic WeatherResponse getDataByCityId(String cityId){String uri= WEATHER_API +"?citykey=" +cityId;return this .doGetWeatherData(uri);}@overridepublic WeatherResponse getDataByCityName (String cityName)1String uri = WEATHER_API +"?city=" + cityName;return this.doGetWeatherData (uri);}private WeatherResponse doGeteatherData(String uri){ValueOperations opS= this.stringRedisTemplate.opsF'orValue();String key - uri;//将调用的UR工作为缓存的keyString strBody = null;//先查缓存,如果没有再查服务if(!this.stringRedisTemplate.hasKey(key)) {logger.info("未找到key " + key);ResponseEntity response= restTemplate.getForEntity(uri,String.class);if(response.getStatusCodeValue(--200) fstrBody =response.getBody (;ops.set(key,strBody,TIME_OUT,TimeUnit.SECONDS);Helse {logger.info("找到key " +key + ",value=" + Ops.get(key));strBody=ops.get(key);objectMapper mapper = new ObjectMapper(;WeatherResponse weather = null;try {weather = mapper.readValue(strBody,WeatherResponse.class);}catch (IOException e){logger.error("JSON反序列化异常!",e);return weather;}}

修改了doGetWeatherData方法,增加了Redis数据的判断。

  • 当存在某个key(天气接口的URI,是唯一代表某个地区的天气数据)时,就可以从Redis 里面取缓存数据。
  • 当不存在某个key(没有初始化数据或数据过期了)时,重新去天气接口里面取最新的数据,并初始化到Redis 中。
  • 由于天气数据更新频率的特点(基本上一个小时或半个小时更新一次),因此,我们在Redis里面设置了30分钟的超时时间。

其中,StringRedisTemplate与RedisTemplate功能类似,都是封装了对Redis的一些常用的操作。

它们的区别在于,StringRedisTemplate更加专注于基于字符串的操作,毕竟,在目前的天气预报应用中,数据的格式主要是JSON字符串。

ValueOperations接口封装了大部分简单的K-V操作。

同时,我们也使用了日志框架来记录运行过程及日常的信息。

测试和运行

首先,在进行测试前,需要将Redis服务器启动起来。

我们可以通过在一个时间段内多次访问同一个天气接口来测试效果,比如接口http:/local-host:8080/weather/cityId/101280601。为了缩短测试的时间,可以将Redis的超时时间缩短一点,如缩短10秒。这样,就不用等30分钟才能验证数据是否过期了。

2017-10-18 23:51:41.762 INFO 15220---[nio-8080-exec-6]:未找到 key http://wthrcdn .C.w.s.c.w.s.WeatherDataServicelmpletouch.cn/weather mini?citykey=1012806012017-10-18 23:51:43.649 INFO 15220 ---[nio-8080-exec-5]:找到key http://wthrcdn .C.w.s.c.w.s.WeatherDataService工mpletouch.cn/weather_mini?citykey=101280601,value={ "data":{ "yesterday":f "date":"17日星期二", "high":"高温29℃","fx":"无持续风向","low":"低温22℃","fl":"","type":"多云"),"city":"深圳", "aqi":"35","forecast":[ ( "date":"18日星期三" , "high":"高温29℃", "fengli":"","low":"低温23℃", "fengxiang":"无持续风向", "type":"多云"),("date":"19日星期四", "high":"高温29℃" , "fengli":"","low":"低温23℃","fengxiang":"无持续风向","type":"多云"),{ "date" :"20日星期五" , "high" :"高温30℃", "fengli":"","low":"低温22℃", "fengxiang":"无持续风向" , "type":"多云"},("date":"21日星期六","high":"高温29℃", "fengli":"", "low":"低温21℃", "fengxiang":"无持续风向", "type":"多云"),{"date":"22日星期天", "high":"高温28℃", "fengli":"","low":"低温21℃","fengxiang ":"无持续风向","type" :"多云")],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒概率较低。","wendu":"25"), "status":1000, "desc":"OK"}2017-10-18 23:51:46.700 INFO 15220---[nio-8080-exec-7]:找到key http://wthrcdn.c.w.s.c.w.s.WeatherDataServiceImpletouch.cn/weather_mini?citykey=101280601,value={ "data":{ "yesterday" :( "-date":"17日星期二","high":"高温29℃","fx":"无持续风向","low":"低温22℃","fl":"","type":"多云"},"city":"深圳", "aqi":"35","forecast":[ {"date":"18日星期三", "high":"高温29℃", "fengli":"","low":"低温23℃","fengxiang":"无持续风向", "type":"多云"),( "date":"19日星期四", "high":"高温29℃" , "fengli" : "","low":"低温23℃","fengxiang":"无持续风向", "type":"多云"},{"date":"20日星期五", "high":"高温30C", "fengli":"","low":"低温22℃","fengxiang":"无持续风向","type":"多云"),{"date":"21日星期六","high":"高温29℃","fengli":"","low":"低温21℃", "Eengxiang":"无持续风向", "type":"多云"),( "date":"22日星期天" , "high":"高温28℃", "fengli" :"","low":"低温21℃","fengxiang":"无持续风向","type":"多云"H],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒概率较低。","wendu":"25"},"status":1000," desc":"OK"}2017-10-18 23:51:50.513 INFO 15220 ---[nio-8080-exec-8]c.w.s.c.w.s.WeatherDataserviceImpl:找到 key http://wthrcdn.etouch.cn/weather_mini?citykey=101280601, value={"data":{ "yesterday":( "date":"17日星期二","high":"高温29℃","fx":"无持续风向","low":"低温22℃","fI":"", "type ":"多云"),"city":"深圳",, "aqi":"35","forecast":[{"date":"18日星期三", "high":"高温29℃", "fengli":"","lowt":"低温23℃","fengxiang":"无持续风向","type" :"多云"),{"date":"19日星期四", "high":"高温29℃", "fengli":"","low":"低温23℃","fengxiang":"无持续风向","type":"多云"),{"date":"20日星期五","high":"高温3o℃","fengli":"","low":"低温22℃","fengxiang":"无持续风向", "type":"多云"},{"date":"21日星期六", "high":"高温29℃", "fengli":"","low":"低温21℃","fengxiang":"无持续风向","type":"多云"),{"date" :"22日星期天","high":"高温28℃","fengli":"","low":"低温21℃","fengxiang":"无持续风向","type":"多云")],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒概率较低。","wendu":"25"),"status":1000, "desc":"OK"}2017-10-18 23:51:53.140 INFO 15220 ---[nio-8080-exec-9] c.w.s.C.W.s.:未找到key http://wthrcdn.etouch.cn/weather_WeatherDataServiceImplmini?citykey=101280601

从上述日志可以看到,第一次(23:51:41)访问接口时,没有找到Redis里面的数据,所以,就初始化了数据。后面几次访问,都是访问Redis里面的数据。最后一次(23:51:53 ),由于超时,Redis里面没有数据了,因此又会拿天气接口的数据。

本篇内容给大家讲解的是使用Redis提升应用的并发访问能力

  1. 下篇文章给大家介绍如何实现天气数据的同步;
  2. 觉得文章不错的朋友可以转发此文关注小编;
  3. 感谢大家的支持!!
a4973ff553bc3460696cf1020fc361ab.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值