- 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>
225 lines
9.1 KiB
Java
225 lines
9.1 KiB
Java
package com.krylov.refound.service;
|
||
|
||
import com.fasterxml.jackson.databind.JsonNode;
|
||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
import com.krylov.refound.dto.AddressInfo;
|
||
import com.krylov.refound.enums.ErrorCode;
|
||
import com.krylov.refound.exception.ApiException;
|
||
import java.io.IOException;
|
||
import java.net.URI;
|
||
import java.net.URLEncoder;
|
||
import java.net.http.HttpClient;
|
||
import java.net.http.HttpRequest;
|
||
import java.net.http.HttpResponse;
|
||
import java.nio.charset.StandardCharsets;
|
||
import java.time.Duration;
|
||
import java.util.List;
|
||
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
|
||
public class GeocodingService {
|
||
|
||
// Поля 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 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"
|
||
+ "&addressdetails=1";
|
||
|
||
HttpRequest request = HttpRequest.newBuilder()
|
||
.uri(URI.create(url))
|
||
.timeout(Duration.ofSeconds(5))
|
||
.header("User-Agent", userAgent)
|
||
.header("Accept-Language", "ru")
|
||
.GET()
|
||
.build();
|
||
|
||
JsonNode root;
|
||
try {
|
||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||
if (response.statusCode() != 200) {
|
||
log.warn("Nominatim вернул статус {} для lat={}, lon={}", response.statusCode(), lat, lon);
|
||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||
}
|
||
root = mapper.readTree(response.body());
|
||
} catch (IOException e) {
|
||
log.error("Ошибка при обращении к Nominatim: {}", e.getMessage(), e);
|
||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||
} catch (InterruptedException e) {
|
||
Thread.currentThread().interrupt();
|
||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||
}
|
||
|
||
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) {
|
||
JsonNode address = root.path("address");
|
||
String displayName = root.path("display_name").asText("");
|
||
|
||
String city = CITY_FIELDS.stream()
|
||
.map(field -> address.path(field).asText(null))
|
||
.filter(value -> value != null && !value.isBlank())
|
||
.findFirst()
|
||
.orElse(null);
|
||
|
||
String district = buildDistrict(displayName, city);
|
||
|
||
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);
|
||
}
|
||
|
||
/**
|
||
* display_name — это склеенные через запятую компоненты адреса от самого точного к самому общему.
|
||
* Убираем из этого списка компонент, совпавший с городом, и склеиваем остальное обратно.
|
||
*/
|
||
private String buildDistrict(String displayName, String city) {
|
||
if (displayName.isBlank()) {
|
||
return null;
|
||
}
|
||
|
||
String[] parts = displayName.split(",");
|
||
StringBuilder result = new StringBuilder();
|
||
boolean cityRemoved = false;
|
||
|
||
for (String part : parts) {
|
||
String trimmed = part.trim();
|
||
if (!cityRemoved && trimmed.equalsIgnoreCase(city)) {
|
||
cityRemoved = true;
|
||
continue;
|
||
}
|
||
if (!result.isEmpty()) {
|
||
result.append(", ");
|
||
}
|
||
result.append(trimmed);
|
||
}
|
||
|
||
return result.isEmpty() ? null : result.toString();
|
||
}
|
||
|
||
private String encode(String value) {
|
||
return URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||
}
|
||
} |