Skip to content

Instantly share code, notes, and snippets.

@sheelprabhakar
Created March 6, 2021 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheelprabhakar/a732d0dad9894ff04fff25ebc4ea0391 to your computer and use it in GitHub Desktop.
Save sheelprabhakar/a732d0dad9894ff04fff25ebc4ea0391 to your computer and use it in GitHub Desktop.
Spring service to generate simulation data for cities temprature
@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