Keep network calls out of post transactions; cache and throttle geocoding
- PostService.create/update geocode and upload photos before opening the DB transaction (TransactionTemplate); uploaded files are removed if the transaction fails, so a DB connection is no longer held while waiting for Nominatim or MinIO. - GeocodingService: configurable URL and User-Agent (geocoding.*), results cached in Redis for 30 days by coordinates rounded to ~11 m, and a cluster-wide 1 request/s slot (geo:throttle) as the public Nominatim policy requires; city/district are cut to the column sizes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,31 +14,74 @@ import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Город и район по координатам (обратное геокодирование, Nominatim/OSM).
|
||||
*
|
||||
* <ul>
|
||||
* <li>Адрес сервиса и User-Agent настраиваются ({@code geocoding.*}): политика
|
||||
* публичного Nominatim требует узнаваемый User-Agent с контактом и не больше
|
||||
* 1 запроса в секунду; для нагрузки лучше свой экземпляр Nominatim.</li>
|
||||
* <li>Результат кэшируется в Redis ({@code geo:<lat>:<lon>}, координаты округлены
|
||||
* до 4 знаков ≈ 11 м) — повторные объявления из того же места не ходят наружу.</li>
|
||||
* <li>Лимит 1 запрос/с общий для всех экземпляров: метка {@code geo:throttle} в Redis.
|
||||
* Если слот за ~1 с не освободился — ApiException 503, и объявление
|
||||
* сохраняется с городом из адреса формы.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class GeocodingService {
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
// Поля address-объекта Nominatim, которые в сумме считаем "городом" (в порядке приоритета)
|
||||
private static final List<String> CITY_FIELDS = List.of("city", "town", "village", "municipality");
|
||||
private static final Duration CACHE_TTL = Duration.ofDays(30);
|
||||
private static final String THROTTLE_KEY = "geo:throttle";
|
||||
private static final int THROTTLE_ATTEMPTS = 5;
|
||||
private static final long THROTTLE_WAIT_MILLIS = 250;
|
||||
/** Колонки posts.city и posts.district. */
|
||||
private static final int CITY_MAX = 100;
|
||||
private static final int DISTRICT_MAX = 500;
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final String baseUrl;
|
||||
private final String userAgent;
|
||||
private final Duration minInterval;
|
||||
|
||||
// HttpClient потокобезопасен и предназначен для переиспользования — не создаём его на каждый запрос
|
||||
private final HttpClient httpClient = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.build();
|
||||
|
||||
public GeocodingService(ObjectMapper mapper, StringRedisTemplate redisTemplate,
|
||||
@Value("${geocoding.url:https://nominatim.openstreetmap.org}") String baseUrl,
|
||||
@Value("${geocoding.user-agent:ReFound-backend/1.0}") String userAgent,
|
||||
@Value("${geocoding.min-interval:PT1S}") Duration minInterval) {
|
||||
this.mapper = mapper;
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
|
||||
this.userAgent = userAgent;
|
||||
this.minInterval = minInterval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Определяет город и остальную часть адреса по координатам через Nominatim reverse geocoding.
|
||||
*/
|
||||
public AddressInfo getAddress(String lat, String lon) {
|
||||
String url = "https://nominatim.openstreetmap.org/reverse"
|
||||
String cacheKey = cacheKey(lat, lon);
|
||||
AddressInfo cached = readCache(cacheKey);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
acquireSlot();
|
||||
String url = baseUrl + "/reverse"
|
||||
+ "?lat=" + encode(lat)
|
||||
+ "&lon=" + encode(lon)
|
||||
+ "&format=jsonv2"
|
||||
@@ -47,7 +90,8 @@ public class GeocodingService {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(5))
|
||||
.header("User-Agent", "MyApp/1.0")
|
||||
.header("User-Agent", userAgent)
|
||||
.header("Accept-Language", "ru")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
@@ -67,7 +111,65 @@ public class GeocodingService {
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return toAddressInfo(root);
|
||||
AddressInfo result = toAddressInfo(root);
|
||||
writeCache(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Ждёт свободный слот общего лимита запросов к геокодеру. */
|
||||
private void acquireSlot() {
|
||||
for (int attempt = 0; attempt < THROTTLE_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
Boolean acquired = redisTemplate.opsForValue().setIfAbsent(THROTTLE_KEY, "1", minInterval);
|
||||
if (Boolean.TRUE.equals(acquired)) {
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// Без Redis общий лимит не соблюсти — идём без него, это редкий случай
|
||||
log.debug("Лимит геокодера не проверен: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(THROTTLE_WAIT_MILLIS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования перегружен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
static String cacheKey(String lat, String lon) {
|
||||
return "geo:" + round(lat) + ":" + round(lon);
|
||||
}
|
||||
|
||||
private static String round(String coordinate) {
|
||||
try {
|
||||
return String.format(java.util.Locale.ROOT, "%.4f", Double.parseDouble(coordinate));
|
||||
} catch (NumberFormatException e) {
|
||||
return coordinate;
|
||||
}
|
||||
}
|
||||
|
||||
private AddressInfo readCache(String key) {
|
||||
try {
|
||||
String json = redisTemplate.opsForValue().get(key);
|
||||
return json == null ? null : mapper.readValue(json, AddressInfo.class);
|
||||
} catch (Exception e) {
|
||||
log.debug("Кэш геокодера недоступен: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCache(String key, AddressInfo info) {
|
||||
if (info.city() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, mapper.writeValueAsString(info), CACHE_TTL);
|
||||
} catch (Exception e) {
|
||||
log.debug("Не удалось сохранить результат геокодера: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private AddressInfo toAddressInfo(JsonNode root) {
|
||||
@@ -82,7 +184,11 @@ public class GeocodingService {
|
||||
|
||||
String district = buildDistrict(displayName, city);
|
||||
|
||||
return new AddressInfo(city, district);
|
||||
return new AddressInfo(truncate(city, CITY_MAX), truncate(district, DISTRICT_MAX));
|
||||
}
|
||||
|
||||
private static String truncate(String value, int max) {
|
||||
return value == null || value.length() <= max ? value : value.substring(0, max);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user