查询天气预报系统之---使用Feign实现天气数据采集微服务(十)

在前面系统中,当时遗留了一些地方我们采用的是硬编码的方式,设置的特定的值,具体请查看:

https://blog.csdn.net/FindHuni/article/details/91415612

https://blog.csdn.net/FindHuni/article/details/91870257

这里我们采用Feign调用方式修改当初遗留的问题

新建项目:springBoot-collection-feign

项目结构:

 

 pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.csq.study</groupId>
  <artifactId>springBoot-collection-feign</artifactId>
  <version>0.0.1-SNAPSHOT</version>
<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.14.RELEASE</version>
	</parent>
	<properties>
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<spring.cloud.version>Edgware.SR5</spring.cloud.version>
	    <quartz.version>2.0.0.RELEASE</quartz.version>
	</properties>
	
	<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-quartz -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-quartz</artifactId>
		    <version>${quartz.version}</version>
			  </dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
			</dependency>
			  <!-- Eureka服务-->
		<dependency>
		    <groupId>org.springframework.cloud</groupId>
		    <artifactId>spring-cloud-starter-eureka</artifactId>
		    </dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
			  </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
      	<dependency>
   		 <groupId>org.springframework.cloud</groupId>
   		 <artifactId>spring-cloud-starter-openfeign</artifactId>
   	
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				</plugin>
		</plugins>
	</build>
</project>

配置类:RestConfiguration

package com.yian.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
 * 配置类

 * @Description: TODO 
 * @ClassName: RestConfiguration
 * @author chengshengqing  2019年2月28日 上午10:25:38
 * @see TODO
 */
@Configuration
public class RestConfiguration {

	@Autowired
	private RestTemplateBuilder builder;
	@Bean
	public RestTemplate restTemplate(){
		return builder.build();
	}
}

定时任务类:ScheduledTasks 

 

package com.yian.springboot.job;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yian.springboot.service.CityClient;
import com.yian.springboot.service.WeatherDataCollectionService;
import com.yian.springboot.vo.City;
@Component
public class ScheduledTasks {

	  private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
	  private static final SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	 
	  
	  @Autowired
	  private WeatherDataCollectionService weatherDataCollectionService;
	  @Autowired
	  private CityClient cityClient;
	    @Scheduled(fixedRate = 30000)
	    public void scheduledDemo(){
	        logger.info("天气数据同步任务 开始  every 5 seconds:{}", formate.format(new Date()) );
	        
	        List<City> cityList=null;
	   
	        try {
				/*cityList = new ArrayList<City>();
	        	City city=new City();
	        	city.setCityId("101280601");
	        	cityList.add(city);*/
	        	cityList=cityClient.listCity();//采用feign的方式调用
			} catch (Exception e) {
				logger.info("获取异常",e);
			}
	        
	       for (City city : cityList) {
	    	   String cityId = city.getCityId();
	    	   logger.info("天气任务同步中,cityId:"+cityId);
	    	   //根据城市id获取天气
	    	   weatherDataCollectionService.syncDataByCityId(cityId);
		}
	       logger.info("天气任务同步End");
	    }
}

接口: CityClient 

 

package com.yian.springboot.service;

import java.util.List;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yian.springboot.vo.City;

@FeignClient("springBoot-city")
public interface CityClient {

	@RequestMapping(value="/cities", method=RequestMethod.GET)
	List<City> listCity() throws Exception;
}

 

WeatherDataCollectionService 接口:

package com.yian.springboot.service;

public interface WeatherDataCollectionService {
     /**
      * 根据城市Id同步天气数据
      * @Title: syncDataByCityId 
      * @Description: TODO 
      * @param cityId
      * @author chengshengqing  2019年6月4日 下午2:35:52
      */
	void syncDataByCityId(String cityId);
}

 

实现类:WeatherDataCollectionServiceImpl

package com.yian.springboot.service;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
 * 
 * @Description: 天气数据采集服务
 * @ClassName: WeatherDataCollectionServiceImpl
 * @author chengshengqing 2019年6月4日 下午2:37:25
 * @see TODO
 */
@Service
public class WeatherDataCollectionServiceImpl implements WeatherDataCollectionService {
	
	
	private final static Logger logger=LoggerFactory.getLogger(WeatherDataCollectionServiceImpl.class);
	
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	private final String WEATHER_API="http://wthrcdn.etouch.cn/weather_mini";
	 //设置超时时间
	private final Long TIME_OUT=1800L;

	@Override
	public void syncDataByCityId(String cityId) {
		logger.info("Start 同步天气 .cityId"+cityId);
		String uri = WEATHER_API + "?citykey=" + cityId;
        this.saveWeatherData(uri);
        
        logger.info("End 同步天气");
	}
	private void saveWeatherData(String uri) {
		String key=uri;
        String strBody = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //调用服务接口来获取
        ResponseEntity<String> respString = restTemplate.getForEntity(uri,String.class);

        //将接口返回的Json字符串转换成对象
        if (respString.getStatusCodeValue() == 200) {
            strBody = respString.getBody();
        }

        //数据写入缓存
        ops.set(key,strBody,TIME_OUT, TimeUnit.SECONDS);
    }
}

 

vo类:City

package com.yian.springboot.vo;


/**
 * 城市vo类
 * @Description: TODO 
 * @ClassName: City
 * @author chengshengqing  2019年6月08日 上午10:06:25
 * @see TODO
 */
public class City{	
	 
	    private String cityId;
	  
	    private String cityName;
	  
	    private String cityCode;
	  
	    private String province;
	
		//省略get/set方法
}

 

配置文件:

#端口号
server.port=8083
#应用名称
spring.application.name=springBoot-collection-feign
#注册服务器的URL
eureka.client.service-url.defaultZone=http://localhost:8762/eureka/
#请求服务时的超时时间
feign.client.config.feignName.connectTimeout=5000
#读数据时的超时时间
feign.client.config.feignName.readyTimeout=5000

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000   

启动类:

package com.yian.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableScheduling
@EnableDiscoveryClient
@EnableFeignClients
public class Aplication {
	public static void main(String[] args) {
		SpringApplication.run(Aplication.class, args);
	}

}

首先启动注册中心、启动redis、在启动springBoot-city ,然后启动该项目,看下打印台:

 

出现上面的同步任务证明消费成功

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值