Created
March 6, 2021 05:08
-
-
Save sheelprabhakar/a732d0dad9894ff04fff25ebc4ea0391 to your computer and use it in GitHub Desktop.
Spring service to generate simulation data for cities temprature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
public class WeatherAgentServiceImpl implements WeatherAgentService { | |
private final CityRepository cityRepository; | |
private final ExecutorService executor; | |
private final KafkaTemplate<String, WeatherInfo> kafkaTemplate; | |
private final Random rand = new Random(); | |
private final int min = -20; | |
private final int max = 50; | |
@Autowired | |
public WeatherAgentServiceImpl(CityRepository cityRepository, KafkaTemplate<String, WeatherInfo> kafkaTemplate) { | |
this.cityRepository = cityRepository; | |
this.kafkaTemplate = kafkaTemplate; | |
this.executor = Executors.newFixedThreadPool(10); | |
} | |
@Override | |
public void update() { | |
Iterable<City> cities = this.cityRepository.findAll(); | |
int i =0; | |
for (City city : cities) { | |
float randomNum = min + rand.nextFloat() * (max - min); | |
this.executor.submit(new WeatherTask(city, randomNum)); | |
} | |
} | |
class WeatherTask implements Callable<Boolean> { | |
private final City city; | |
private final float temp; | |
public WeatherTask(final City city, float temp) { | |
this.city = city; | |
this.temp = temp; | |
} | |
@Override | |
public Boolean call() throws Exception { | |
WeatherInfo info = new WeatherInfo(city.getName(), city.getLatitude(), city.getLongitude(), temp); | |
kafkaTemplate.send("weather-log2",""+info.getLogDate().getTimeInMillis(), info); | |
System.out.println(city.getName() + ":" +temp); | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment