master
周宇恒 2024-02-07 09:33:26 +08:00
parent 119d3fefa9
commit 6ac7a6db1d
42 changed files with 1730 additions and 0 deletions

View File

@ -7,6 +7,8 @@
<file url="file://$PROJECT_DIR$/community-security-common/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-common/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-gateway/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-gateway/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-gateway/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-gateway/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-es/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-photo/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-shop/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-shop/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-shop/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-shop/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-system/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/community-security-modules/community-security-modules-system/src/main/java" charset="UTF-8" />

View File

@ -117,6 +117,19 @@
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version> <!-- 使用你需要的版本 -->
</dependency>
</dependencies> </dependencies>

View File

@ -0,0 +1,12 @@
package com.zyh.common.domain;
import lombok.Data;
@Data
public class Camera {
private Integer id;
private String cameraId;
private Double lng;
private Double lat;
private String address;
}

View File

@ -0,0 +1,224 @@
package com.zyh.common.domain;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CompreFaceApiResponse {
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
public static class Result {
private Age age;
private Gender gender;
private Pose pose;
private Box box;
private List<Subject> subjects;
private List<List<Integer>> landmarks;
public Age getAge() {
return age;
}
public void setAge(Age age) {
this.age = age;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Pose getPose() {
return pose;
}
public void setPose(Pose pose) {
this.pose = pose;
}
public Box getBox() {
return box;
}
public void setBox(Box box) {
this.box = box;
}
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public List<List<Integer>> getLandmarks() {
return landmarks;
}
public void setLandmarks(List<List<Integer>> landmarks) {
this.landmarks = landmarks;
}
}
public static class Age {
private Double probability;
private Integer high;
private Integer low;
public Double getProbability() {
return probability;
}
public void setProbability(Double probability) {
this.probability = probability;
}
public Integer getHigh() {
return high;
}
public void setHigh(Integer high) {
this.high = high;
}
public Integer getLow() {
return low;
}
public void setLow(Integer low) {
this.low = low;
}
}
public static class Gender {
private Double probability;
private String value;
public Double getProbability() {
return probability;
}
public void setProbability(Double probability) {
this.probability = probability;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static class Pose {
private Double pitch;
private Double roll;
private Double yaw;
public Double getPitch() {
return pitch;
}
public void setPitch(Double pitch) {
this.pitch = pitch;
}
public Double getRoll() {
return roll;
}
public void setRoll(Double roll) {
this.roll = roll;
}
public Double getYaw() {
return yaw;
}
public void setYaw(Double yaw) {
this.yaw = yaw;
}
}
public static class Box {
private Double probability;
private Integer xMax;
private Integer yMax;
private Integer xMin;
private Integer yMin;
public Double getProbability() {
return probability;
}
public void setProbability(Double probability) {
this.probability = probability;
}
public Integer getxMax() {
return xMax;
}
public void setxMax(Integer xMax) {
this.xMax = xMax;
}
public Integer getyMax() {
return yMax;
}
public void setyMax(Integer yMax) {
this.yMax = yMax;
}
public Integer getxMin() {
return xMin;
}
public void setxMin(Integer xMin) {
this.xMin = xMin;
}
public Integer getyMin() {
return yMin;
}
public void setyMin(Integer yMin) {
this.yMin = yMin;
}
}
public static class Subject {
private String subject;
private Double similarity;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Double getSimilarity() {
return similarity;
}
public void setSimilarity(Double similarity) {
this.similarity = similarity;
}
}
}

View File

@ -0,0 +1,11 @@
package com.zyh.common.domain;
import lombok.Data;
@Data
public class Dataa {
private String faceId;
private Integer score;
private String iccard;
private Integer role;
}

View File

@ -0,0 +1,29 @@
package com.zyh.common.domain;
import lombok.Data;
@Data
public class Photo {
private Integer act;
private Integer x;
private Integer y;
private Integer w;
private Integer h;
private Integer datetime;
private Integer age;
private Integer gender;
private Integer glasses;
private Integer mask;
private Integer race;
private Integer beard;
private Integer expression;
private Integer hat;
private Dataa Data;
private String extend_idcard;
private String mac;
private String ip;
private String image;
}

View File

@ -0,0 +1,109 @@
package com.zyh.common.util;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.common.result.Result;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
public class ComprefaceUtils {
private static final String BASE_URL = "http://100.96.85.95:8000";
private static final String VERIFICATION_API_KEY = "1596cf9c-8426-41bf-ad3e-cb3b126533ab";
// public static String verifyFace(String base64Image, String limit, String detProbThreshold, String facePlugins, String status) {
// try {
// // 对参数进行 URL 编码
// limit = URLEncoder.encode(limit, StandardCharsets.UTF_8);
// detProbThreshold = URLEncoder.encode(detProbThreshold, StandardCharsets.UTF_8);
// facePlugins = URLEncoder.encode(facePlugins, StandardCharsets.UTF_8);
// status = URLEncoder.encode(status, StandardCharsets.UTF_8);
//
// // 构建请求URL
// String apiUrl = BASE_URL + "/api/v1/verification/verify?limit=" + limit +
// "&det_prob_threshold=" + detProbThreshold + "&face_plugins=" + facePlugins +
// "&status=" + status;
//
// // 构建请求头
// HttpClient httpClient = HttpClients.createDefault();
// HttpPost httpPost = new HttpPost(apiUrl);
// httpPost.setHeader("Content-Type", "application/json");
// httpPost.setHeader("x-api-key", VERIFICATION_API_KEY);
//
// // 构建请求体
// String requestBody = "{\"base64Image\":\"" + base64Image + "\"}";
// httpPost.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
//
// // 发送请求并获取响应
// HttpResponse response = httpClient.execute(httpPost);
// HttpEntity entity = response.getEntity();
//
// // 处理响应
// if (entity != null) {
// return EntityUtils.toString(entity);
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return null;
// }
public static Result<CompreFaceApiResponse.Result> recognizeFace(byte[] imageData) {
try {
String apiUrl = BASE_URL + "/api/v1/recognition/recognize?limit=0&det_prob_threshold=0.8&prediction_count=1&face_plugins=landmarks%2C%20gender%2C%20age%2C%20calculator%2C%20mask%2C%20pose&status=true";
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("x-api-key", VERIFICATION_API_KEY);
// 将字节数组转换为Base64编码的字符串
String base64Image = Base64.getEncoder().encodeToString(imageData);
// 设置请求体
String requestBody = "{\"file\": \"" + base64Image + "\"}";
// 发起POST请求
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<CompreFaceApiResponse> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, CompreFaceApiResponse.class);
// 处理响应
if (responseEntity.getStatusCode().is2xxSuccessful()) {
CompreFaceApiResponse response = responseEntity.getBody();
List<CompreFaceApiResponse.Result> faceResults = response.getResult();
CompreFaceApiResponse.Result result = faceResults.get(0);
System.out.println("Response: " + result);
return Result.success(result);
} else {
System.err.println("Error: " + responseEntity.getStatusCode());
return Result.error("解析失败:" + responseEntity.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
return Result.error("解析失败:" + e.getMessage()) ;
}
}
}

View File

@ -0,0 +1,48 @@
package com.zyh.common.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
public class ImageToBase64Converter {
public static String convertImageToBase64(String imagePath) {
String base64Image = "";
Path path = Paths.get(imagePath);
try {
byte[] imageBytes = Files.readAllBytes(path);
base64Image = Base64.getEncoder().encodeToString(imageBytes);
} catch (Exception e) {
e.printStackTrace();
}
return base64Image;
}
public static void main(String[] args) {
String imagePath = "/path/to/your/image.jpg"; // 替换为实际的图片路径
String base64Image = convertImageToBase64(imagePath);
System.out.println(base64Image);
}
public static String convertToBase64(MultipartFile image) {
try {
byte[] bytes = image.getBytes();
return Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
// 处理异常
e.printStackTrace();
return null;
}
}
public static String convertBlobToBase64(byte[] blobData) {
// 使用 Base64 类将字节数组转换为 Base64 编码的字符串
return Base64.getEncoder().encodeToString(blobData);
}
}

View File

@ -0,0 +1,25 @@
package com.zyh.common.util;
import java.security.SecureRandom;
public class RandomGenerator {
public static String generateRandomLetters(int length) {
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder randomString = new StringBuilder(length);
SecureRandom random = new SecureRandom();
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(letters.length());
char randomChar = letters.charAt(randomIndex);
randomString.append(randomChar);
}
return randomString.toString();
}
public static void main(String[] args) {
String randomLetters = generateRandomLetters(5);
System.out.println("Random Letters: " + randomLetters);
}
}

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>com.zyh</groupId>
<artifactId>community-security-modules</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>community-security-modules-es</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 系统公共 依赖 -->
<dependency>
<groupId>com.zyh</groupId>
<artifactId>community-security-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Kafka dependencies -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
package com.zyh.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
@SpringBootApplication
@EnableKafka
public class EsApplication {
public static void main(String[] args) {
SpringApplication.run(EsApplication.class, args);
System.out.println("Es启动成功");
}
}

View File

@ -0,0 +1,25 @@
package com.zyh.es.config;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "es")
@Data
public class InitEsRes {
private String host;
private int port;
private String scheme;
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(new HttpHost(host,port,scheme))
);
}
}

View File

@ -0,0 +1,8 @@
package com.zyh.es.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EsController {
}

View File

@ -0,0 +1,56 @@
//package com.zyh.es.kafka;
//
//import cn.hutool.core.date.DateUtil;
//import org.apache.kafka.clients.consumer.ConsumerConfig;
//import org.apache.kafka.clients.consumer.ConsumerRecord;
//import org.apache.kafka.clients.consumer.ConsumerRecords;
//import org.apache.kafka.clients.consumer.KafkaConsumer;
//import org.apache.kafka.common.serialization.StringDeserializer;
//
//import java.time.Duration;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.Properties;
//
//public class Consumer {
// public final static String groupId = "face";
// public final static String bootstrapServers = "152.136.54.230:9092";
//
// public static KafkaConsumer<String, String> kafkaConsumer() {
// Properties props = new Properties();
// //设置Kafka服务器地址
// props.put("bootstrap.servers", bootstrapServers);
// //设置消费组
// props.put("group.id", groupId);
// //设置数据key的反序列化处理类
// props.put("key.deserializer", StringDeserializer.class.getName());
// //设置数据value的反序列化处理类
// props.put("value.deserializer", StringDeserializer.class.getName());
// props.put("enable.auto.commit", "true");
// props.put("auto.commit.interval.ms", "1000");
// props.put("session.timeout.ms", "30000");
// //设置偏移量
// props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(props);
// //订阅名称为“xjx”的Topic的消息
// kafkaConsumer.subscribe(Arrays.asList("face"));
// return kafkaConsumer;
// }
//
// public static void main(String[] args) {
// //从Kafka服务器中的名称为“face”的Topic中消费消息
// KafkaConsumer<String,String> kafkaConsumer = kafkaConsumer();
// //List<String> messages = new ArrayList<>(records.count());
// for (;;) {
// ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofSeconds(1));
// for (ConsumerRecord<String, String> record : records.records("face")) {
// String value = record.value();
// System.out.print("time:"+DateUtil.formatDateTime(new Date(record.timestamp()))+",");
// System.out.print("value:"+value+",");
// System.out.println("offset:"+record.offset());
// }
// System.out.println("--------------------------------");
// }
// }
//}
//

View File

@ -0,0 +1,67 @@
//package com.zyh.es.kafka;
//
//import com.zyh.common.domain.CompreFaceApiResponse;
//import com.zyh.es.service.EsService;
//import com.zyh.es.service.impl.EsServicempl;
//import org.apache.kafka.clients.consumer.ConsumerConfig;
//import org.apache.kafka.clients.consumer.ConsumerRecord;
//import org.apache.kafka.clients.consumer.ConsumerRecords;
//import org.apache.kafka.clients.consumer.KafkaConsumer;
//import org.apache.kafka.common.serialization.StringDeserializer;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.PostConstruct;
//import java.time.Duration;
//import java.util.Collections;
//import java.util.Properties;
//
//@Service
//public class KafkaConsumerService {
// private static final String GROUP_ID = "face";
// private final static String TOPIC = "face";
//
// @Autowired
// private EsServicempl esServicempl;
//
// @PostConstruct
// public void init() {
// Properties properties = new Properties();
// // Kafka服务器地址多个地址用逗号分隔
// properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "152.136.54.230:9092");
// // 消费者所属的分组ID
// properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
// // 是否自动提交偏移量默认为true
// properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
// // 自动提交偏移量的时间间隔
// properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
// // 会话超时时间
// properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
// // 一次最大拉取的记录数
// properties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1000);
// // 消费规则默认earliest
// properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// // 键的反序列化器
// properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
// // 值的反序列化器
// properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
//
// KafkaConsumer<String, CompreFaceApiResponse.Result> kafkaConsumer = new KafkaConsumer<>(properties);
// // 订阅主题
// kafkaConsumer.subscribe(Collections.singletonList(TOPIC));
//
// try {
// while (true) {
// // 从Kafka中拉取消息
// ConsumerRecords<String, CompreFaceApiResponse.Result> records = kafkaConsumer.poll(Duration.ofMillis(100));
// for (ConsumerRecord<String, CompreFaceApiResponse.Result> record : records) {
// // 处理消息
// CompreFaceApiResponse.Result data = record.value();
// esServicempl.pushToElasticsearch(data);
// }
// }
// } finally {
// kafkaConsumer.close();
// }
// }
//}

View File

@ -0,0 +1,30 @@
//package com.zyh.es.kafka;
//
//import com.zyh.common.domain.CompreFaceApiResponse;
//import com.zyh.es.service.impl.EsServicempl;
//import org.apache.kafka.clients.consumer.ConsumerRecord;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.annotation.KafkaListener;
//import org.springframework.stereotype.Service;
//
//@Service
//public class KafkaConsumerServiceTest {
// @Autowired
// private EsServicempl esServicempl;
//
// private static final String GROUPID = "face";
// @KafkaListener(topics = "face", groupId = "face")
// public void listen(ConsumerRecord<String, CompreFaceApiResponse.Result> record) {
// try {
// // 从消息中获取数据
// CompreFaceApiResponse.Result data = record.value();
//
// // 将数据推送到 Elasticsearch
// esServicempl.pushToElasticsearch(data);
// } catch (Exception e) {
// // 处理异常(例如,记录日志或采取适当的措施)
// e.printStackTrace();
// }
// }
//
//}

View File

@ -0,0 +1,58 @@
package com.zyh.es.mq;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.zyh.common.constants.RabbitMQQueueNameConstants;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.es.service.impl.EsServicempl;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Component
@Log4j2
public class Clicknum {
@Autowired
private EsServicempl esServicempl;
@Autowired
RedisTemplate<String, String> redisTemplate;
@RabbitListener(queuesToDeclare = {@Queue(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME)})
public void SendCodeMq(String jsonString, Message message, Channel channel) throws JsonProcessingException {
long l = System.currentTimeMillis();
log.info("短信消费者队列开始消费...,消费内容为:{}", jsonString);
String messageId = message.getMessageProperties().getMessageId();
ObjectMapper objectMapper = new ObjectMapper();
CompreFaceApiResponse.Result result = objectMapper.readValue(jsonString, CompreFaceApiResponse.Result.class);
esServicempl.pushToElasticsearch(result);
try {
Long count = redisTemplate.opsForSet().add(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME, messageId);
if (count == 1) {
log.info("短信消费者队列消费成功,耗时:{}毫秒!", System.currentTimeMillis()-l);
}else{
log.info("短信消费者队列重复消费,消费内容为:{}", jsonString);
}
} catch (Exception e) {
log.info("短信消费者队列消费失败,异常内容为:{}", e.getMessage());
redisTemplate.opsForSet().remove(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME, messageId);
try {
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
} catch (Exception ex) {
log.info("短信消费者队列回退失败,异常内容为:{}", ex.getMessage());
}
}
}
}

View File

@ -0,0 +1,4 @@
package com.zyh.es.service;
public interface EsService {
}

View File

@ -0,0 +1,48 @@
package com.zyh.es.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.es.service.EsService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class EsServicempl implements EsService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private ObjectMapper objectMapper;
private final static String INDEX_NAME = "face";
public void pushToElasticsearch(CompreFaceApiResponse.Result data) {
try {
IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
// 不设置文档 ID由 Elasticsearch 自动生成一个唯一 ID
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(
new IndexRequest(INDEX_NAME)
.source(JSONObject.toJSONString(data), XContentType.JSON)
);
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
// 可以根据 indexResponse 获取有关索引操作的信息
System.out.println("Elasticsearch Index Response: " + bulk);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,31 @@
server:
port: 9007
spring:
main:
allow-circular-references: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
name: community-security-modules-es
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
server-addr: 124.221.193.62:8848
namespace: e3afd3fd-73b0-4ac1-9f9e-aad1a8aa9f46
config:
serverAddr: 124.221.193.62:8848
namespace: e3afd3fd-73b0-4ac1-9f9e-aad1a8aa9f46
fileExtension: yml
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
# Elasticsearch
#es:
# host: 152.136.54.230
# port: 9200
# scheme: http

View File

@ -0,0 +1,51 @@
//package com.zyh.es.service.impl;
//
//import org.apache.kafka.clients.consumer.ConsumerConfig;
//import org.apache.kafka.clients.consumer.ConsumerRecords;
//import org.apache.kafka.clients.consumer.KafkaConsumer;
//import org.apache.kafka.common.serialization.StringDeserializer;
//import org.junit.jupiter.api.Test;
//
//import java.time.Duration;
//import java.util.Collections;
//import java.util.Properties;
//
//import static org.junit.jupiter.api.Assertions.*;
//
//class EsServicemplTest {
// @Test
// public void testGet() throws InterruptedException {
// // 主题
// String topic = "product_post";
//
// // 配置
// Properties properties = new Properties();
// // Kafka 服务器地址
// properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "152.136.54.230:9092");
// // kv 的反序列化器
// properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
// properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
//
// // 消费者分组
// properties.put(ConsumerConfig.GROUP_ID_CONFIG, "Consumer-Group-1");
// // Offset 重置模式
// properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
//
// // 消费者
// KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
// // 订阅(可以订阅多个主题)
// kafkaConsumer.subscribe(Collections.singletonList(topic));
//
// // 消费
// while (true) {
// // 获取信息
// ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
// // 遍历
// records.forEach(record -> {
// System.out.println(String.format("topic==%s, offset==%s, key==%s, value==%s", record.topic(), record.offset(), record.key(), record.value()));
// });
// // 睡眠
// Thread.sleep(500);
// }
// }
//}

View File

@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>com.zyh</groupId>
<artifactId>community-security-modules</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>community-security-modules-photo</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 系统公共 依赖 -->
<dependency>
<groupId>com.zyh</groupId>
<artifactId>community-security-common</artifactId>
</dependency>
<!-- SpringBoot Web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis 依赖配置 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.5</version>
</dependency>
<!-- 阿里云oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version> <!-- 使用你需要的版本 -->
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,18 @@
package com.zyh.system;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableKafka
public class PhotoApplication {
public static void main(String[] args) {
SpringApplication.run(PhotoApplication.class, args);
System.out.println("Photo启动成功");
}
}

View File

@ -0,0 +1,43 @@
package com.zyh.system.controller;
import com.zyh.common.domain.Camera;
import com.zyh.common.result.Result;
import com.zyh.system.service.CameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("camera")
public class CameraController {
@Autowired
private CameraService cameraService;
//设备列表
@PostMapping("/cameraList")
public Result<List<Camera>> cameraList() {
return Result.success(cameraService.cameraList());
}
//删除设备
@PostMapping("/cameraDelete")
public Result cameraDelete(@RequestParam Integer id) {
return cameraService.cameraDelete(id);
}
//添加设备
@PostMapping("/cameraAdd")
public Result cameraAdd(@RequestBody Camera camera) {
return cameraService.cameraAdd(camera);
}
//修改设备
@PostMapping("/cameraUpdate")
public Result cameraUpdate(@RequestBody Camera camera) {
return cameraService.cameraUpdate(camera);
}
}

View File

@ -0,0 +1,32 @@
package com.zyh.system.controller;
import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.C;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.common.domain.Photo;
import com.zyh.common.result.Result;
import com.zyh.system.mapper.ComprefaceMapper;
import com.zyh.system.service.ComprefaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("compreFace")
public class ComprefaceController {
@Autowired
private ComprefaceService comprefaceService;
@PostMapping("/compreFace")
public Result<CompreFaceApiResponse.Result> compareFaces(@RequestParam("file") MultipartFile file) throws IOException {
// 调用Compreface服务进行人脸比对
return comprefaceService.compareWithSingleFace(file);
}
}

View File

@ -0,0 +1,70 @@
//package com.zyh.system.kafka;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.zyh.common.domain.CompreFaceApiResponse;
//import org.apache.kafka.clients.producer.ProducerConfig;
//import org.apache.kafka.clients.producer.ProducerRecord;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.kafka.core.KafkaTemplate;
//import org.springframework.kafka.support.SendResult;
//import org.springframework.stereotype.Service;
//import org.springframework.util.concurrent.ListenableFuture;
//import org.springframework.util.concurrent.ListenableFutureCallback;
//
//import javax.annotation.PostConstruct;
//import java.util.Properties;
//
//@Service
//public class KafkaProducerService {
//
// @Autowired
// private KafkaTemplate<String, String> kafkaTemplate;
//
// private final static String topic="face";
//
//
// @PostConstruct
// public void startProducing(CompreFaceApiResponse.Result data) {
// Properties properties = new Properties();
// // 设置 Kafka 生产者配置
// properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "152.136.54.230:9092");
// properties.put("acks", "all");
// properties.put("retries", 0);
// properties.put("batch.size", 16384);
// properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
// properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
//
// try {
// // 使用 Jackson 库将对象转换为 JSON 字符串
// ObjectMapper objectMapper = new ObjectMapper();
// String jsonString = objectMapper.writeValueAsString(data);
//
// // 发送 JSON 字符串到 Kafka
// ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, jsonString);
//
// // 添加回调,处理发送结果
// future.addCallback(new ListenableFutureCallback<>() {
// @Override
// public void onSuccess(SendResult<String, String> result) {
// // 处理成功的逻辑
// System.out.println("消息成功发送到主题: " + result.getRecordMetadata().topic());
// System.out.println("消息成功发送到分区: " + result.getRecordMetadata().partition());
// System.out.println("消息成功发送到偏移量: " + result.getRecordMetadata().offset());
// }
//
// @Override
// public void onFailure(Throwable ex) {
// // 处理失败的逻辑
// System.out.println("消息发送失败: " + ex.getMessage());
// }
// });
//
// } catch (JsonProcessingException e) {
// // 处理转换异常
// e.printStackTrace();
// System.out.println("消息发送失败: " + e.getMessage());
// }
// }
//}

View File

@ -0,0 +1,53 @@
//package com.zyh.system.kafka;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.zyh.common.domain.CompreFaceApiResponse;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.core.KafkaTemplate;
//import org.springframework.kafka.support.SendResult;
//import org.springframework.stereotype.Service;
//import org.springframework.util.concurrent.ListenableFuture;
//import org.springframework.util.concurrent.ListenableFutureCallback;
//
//@Service
//public class KafkaProducerServiceTest {
//
// @Autowired
// private ObjectMapper objectMapper;
// @Autowired
// private KafkaTemplate<String, String> kafkaTemplate;
//
// public void sendMessage(String topic, CompreFaceApiResponse.Result data) {
// try {
// // 使用 Jackson 库将对象转换为 JSON 字符串
// ObjectMapper objectMapper = new ObjectMapper();
// String jsonString = objectMapper.writeValueAsString(data);
//
// // 发送 JSON 字符串到 Kafka
// ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, jsonString);
//
// // 添加回调,处理发送结果
// future.addCallback(new ListenableFutureCallback<>() {
// @Override
// public void onSuccess(SendResult<String, String> result) {
// // 处理成功的逻辑
// System.out.println("消息成功发送到主题: " + result.getRecordMetadata().topic());
// System.out.println("消息成功发送到分区: " + result.getRecordMetadata().partition());
// System.out.println("消息成功发送到偏移量: " + result.getRecordMetadata().offset());
// }
//
// @Override
// public void onFailure(Throwable ex) {
// // 处理失败的逻辑
// System.out.println("消息发送失败: " + ex.getMessage());
// }
// });
//
// } catch (JsonProcessingException e) {
// // 处理转换异常
// e.printStackTrace();
// System.out.println("消息发送失败: " + e.getMessage());
// }
// }
//}

View File

@ -0,0 +1,61 @@
//package com.zyh.system.kafka;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.zyh.common.domain.CompreFaceApiResponse;
//import org.apache.kafka.clients.producer.KafkaProducer;
//import org.apache.kafka.clients.producer.ProducerConfig;
//import org.apache.kafka.clients.producer.ProducerRecord;
//import org.springframework.stereotype.Component;
//
//import java.util.Properties;
//@Component
//public class Producer {
// private static final String brokerList = "152.136.54.230:9092";
// private static final String topic = "face";
//
// public static Properties initNewConfig() {
// Properties props = new Properties();
// props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
// props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
// "org.apache.kafka.common.serialization.StringSerializer");
// props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
// "org.apache.kafka.common.serialization.StringSerializer");
// props.put(ProducerConfig.CLIENT_ID_CONFIG, "producer.client.id.demo");
//
// // 自定义分区器的使用
// //props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,DefinePartitioner.class.getName());
// // 自定义拦截器使用
// //props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,ProducerInterceptorPrefix.class.getName());
// props.put(ProducerConfig.ACKS_CONFIG, "0");
// return props;
// }
//
//
// public static void send(CompreFaceApiResponse.Result data) throws InterruptedException, JsonProcessingException {
// ObjectMapper objectMapper = new ObjectMapper();
// String jsonString = objectMapper.writeValueAsString(data);
// Properties props = initNewConfig();
// KafkaProducer<String, String> producer = new KafkaProducer<>(props);
//
// //KafkaProducer<String, String> producer = new KafkaProducer<>(props,
// //new StringSerializer(), new StringSerializer());
// //生成 ProducerRecord 对象,并制定 Topickey 以及 value
// ProducerRecord<String, String> record =
// new ProducerRecord<>(topic, jsonString);
// try {
// // 1、发送消息
// producer.send(record);
// // 打印成功发送的日志
// System.out.println("消息成功发送到主题: " + topic);
// } catch (Exception e) {
// e.printStackTrace();
// // 打印发送失败的日志
// System.out.println("消息发送失败: " + e.getMessage());
// }
//
//
// producer.close();
// }
//
//}

View File

@ -0,0 +1,18 @@
package com.zyh.system.mapper;
import com.zyh.common.domain.Camera;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface CameraMapper {
List<Camera> cameraList();
Integer cameraDelete(@Param("id") Integer id);
Integer cameraAdd(Camera camera);
Integer cameraUpdate(Camera camera);
}

View File

@ -0,0 +1,8 @@
package com.zyh.system.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ComprefaceMapper {
}

View File

@ -0,0 +1,55 @@
//package com.zyh.system.mq;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.rabbitmq.client.Channel;
//import com.zyh.common.constants.RabbitMQQueueNameConstants;
//import com.zyh.common.domain.CompreFaceApiResponse;
//import lombok.extern.log4j.Log4j2;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.annotation.Queue;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.stereotype.Component;
//
//import java.util.HashMap;
//
//@Component
//@Log4j2
//public class Clicknum {
//
// @Autowired
// RedisTemplate<String, String> redisTemplate;
//
// @RabbitListener(queuesToDeclare = {@Queue(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME)})
// public void SendCodeMq(String jsonString, Message message, Channel channel) throws JsonProcessingException {
// long l = System.currentTimeMillis();
// log.info("短信消费者队列开始消费...,消费内容为:{}", jsonString);
// String messageId = message.getMessageProperties().getMessageId();
//
// ObjectMapper objectMapper = new ObjectMapper();
// CompreFaceApiResponse.Result result = objectMapper.readValue(jsonString, CompreFaceApiResponse.Result.class);
//
//
// try {
// Long count = redisTemplate.opsForSet().add(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME, messageId);
// if (count == 1) {
//
// log.info("短信消费者队列消费成功,耗时:{}毫秒!", System.currentTimeMillis()-l);
// }else{
// log.info("短信消费者队列重复消费,消费内容为:{}", jsonString);
// }
//
// } catch (Exception e) {
// log.info("短信消费者队列消费失败,异常内容为:{}", e.getMessage());
// redisTemplate.opsForSet().remove(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME, messageId);
//
// try {
// channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
// } catch (Exception ex) {
// log.info("短信消费者队列回退失败,异常内容为:{}", ex.getMessage());
// }
// }
// }
//}

View File

@ -0,0 +1,16 @@
package com.zyh.system.service;
import com.zyh.common.domain.Camera;
import com.zyh.common.result.Result;
import java.util.List;
public interface CameraService {
List<Camera> cameraList();
Result cameraDelete(Integer id);
Result cameraAdd(Camera camera);
Result cameraUpdate(Camera camera);
}

View File

@ -0,0 +1,12 @@
package com.zyh.system.service;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.common.domain.Photo;
import com.zyh.common.result.Result;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface ComprefaceService {
Result<CompreFaceApiResponse.Result> compareWithSingleFace(MultipartFile targetImage) throws IOException;
}

View File

@ -0,0 +1,4 @@
package com.zyh.system.service;
public interface EsService {
}

View File

@ -0,0 +1,59 @@
package com.zyh.system.service.impl;
import com.zyh.common.domain.Camera;
import com.zyh.common.result.Result;
import com.zyh.common.util.RandomGenerator;
import com.zyh.system.mapper.CameraMapper;
import com.zyh.system.service.CameraService;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Random;
@Service
public class CameraServicempl implements CameraService {
@Autowired
private CameraMapper cameraMapper;
@Override
public List<Camera> cameraList() {
List<Camera> cameraList = cameraMapper.cameraList();
return cameraList;
}
@Override
public Result cameraDelete(Integer id) {
Integer result = cameraMapper.cameraDelete(id);
if(result>0){
return Result.success("删除成功");
}
return Result.error("删除失败");
}
@Override
public Result cameraAdd(Camera camera) {
//五位字母随机
String s = RandomGenerator.generateRandomLetters(5);
camera.setCameraId(s);
Integer result = cameraMapper.cameraAdd(camera);
if(result>0){
return Result.success("添加成功");
}
return Result.error("添加失败");
}
@Override
public Result cameraUpdate(Camera camera) {
Integer result = cameraMapper.cameraUpdate(camera);
if(result>0){
return Result.success("修改成功");
}
return Result.error("修改失败");
}
}

View File

@ -0,0 +1,52 @@
package com.zyh.system.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.common.constants.RabbitMQQueueNameConstants;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.common.result.Result;
import com.zyh.common.util.ComprefaceUtils;
import com.zyh.system.mapper.ComprefaceMapper;
import com.zyh.system.service.ComprefaceService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@Service
public class ComprefaceServicempl implements ComprefaceService {
@Autowired
private ComprefaceMapper comprefaceMapper;
@Autowired
private EsServicempl esServicempl;
@Autowired
RabbitTemplate rabbitTemplate;
@Override
public Result<CompreFaceApiResponse.Result> compareWithSingleFace(MultipartFile targetImage) throws IOException {
byte[] bytes = targetImage.getBytes();
// 将接收到的图片路径转换为 base64
Result<CompreFaceApiResponse.Result> result = ComprefaceUtils.recognizeFace(bytes);
CompreFaceApiResponse.Result data = result.getData();
// esServicempl.add(data);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(data);
rabbitTemplate.convertAndSend(RabbitMQQueueNameConstants.SEND_SMS_QUEUE_NAME, jsonString,message -> {
message.getMessageProperties().setMessageId(UUID.randomUUID().toString().replaceAll("-", ""));
return message;
});
return Result.success(data);
}
}

View File

@ -0,0 +1,60 @@
package com.zyh.system.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zyh.common.domain.CompreFaceApiResponse;
import com.zyh.system.service.EsService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class EsServicempl implements EsService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private ObjectMapper objectMapper;
private final static String INDEX_NAME = "face";
public void pushToElasticsearch(CompreFaceApiResponse.Result data) {
try {
IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
// 不设置文档 ID由 Elasticsearch 自动生成一个唯一 ID
// indexRequest.id(data.getYourId());
String jsonData = objectMapper.writeValueAsString(data);
indexRequest.source(jsonData, XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
// 可以根据 indexResponse 获取有关索引操作的信息
System.out.println("Elasticsearch Index Response: " + indexResponse);
} catch (IOException e) {
e.printStackTrace();
}
}
public void add(CompreFaceApiResponse.Result data) {
try {
IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
.source(JSONObject.toJSONString(data), XContentType.JSON);
restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,36 @@
package com.zyh.system.util;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public class KafkaMessageConsumer {
public static void main(String[] args) {
// 配置 Kafka 消费者
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "152.136.54.230:9092");
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "face");
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
// 创建 Kafka 消费者
Consumer<String, String> consumer = new KafkaConsumer<>(properties);
// 订阅主题
consumer.subscribe(Collections.singletonList("face"));
// 持续消费消息
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); // 设置轮询时间
records.forEach(record -> {
// 处理消息
System.out.printf("Consumed record with key %s and value %s%n", record.key(), record.value());
});
}
}
}

View File

@ -0,0 +1,38 @@
# Tomcat
server:
port: 9006
# Spring
spring:
main:
allow-circular-references: true
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
application:
# 应用名称
name: community-security-modules-photo
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 124.221.193.62:8848
namespace: e3afd3fd-73b0-4ac1-9f9e-aad1a8aa9f46
config:
# 配置中心地址
server-addr: 124.221.193.62:8848
namespace: e3afd3fd-73b0-4ac1-9f9e-aad1a8aa9f46
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
# Elasticsearch
#es:
# host: 152.136.54.230
# port: 9200
# scheme: http

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zyh.system.mapper.CameraMapper">
<insert id="cameraAdd">
insert into camera
values (0, #{cameraId}, #{lng}, #{lat}, #{address})
</insert>
<update id="cameraUpdate">
update camera
set camera_id = #{cameraId}, lng = #{lng}, lat = #{lat}, address = #{address}
where id = #{id}
</update>
<delete id="cameraDelete">
delete
from camera
where id = #{id}
</delete>
<select id="cameraList" resultType="com.zyh.common.domain.Camera">
select * from camera
</select>
</mapper>

View File

@ -0,0 +1,44 @@
//package com.zyh.system.service.impl;
//
//import com.fasterxml.jackson.databind.ser.std.StringSerializer;
//import org.apache.kafka.clients.producer.KafkaProducer;
//import org.apache.kafka.clients.producer.ProducerConfig;
//import org.apache.kafka.clients.producer.ProducerRecord;
//import org.junit.jupiter.api.Test;
//
//import java.util.Properties;
//
//import static org.junit.jupiter.api.Assertions.*;
//
//class CameraServicemplTest {
//
// @Test
// public void testPost(){
// //主题(当主题不存在,自动创建主题)
// String topic = "product_post";
// //配置
// Properties properties = new Properties();
// //kafka服务器地址
// properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"152.136.54.230:9092");
// //反序列化器
// properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringSerializer.class);
// properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringSerializer.class);
//
// //生产者
// KafkaProducer<String,String> kafkaProducer = new KafkaProducer(properties);
//
// //生产信息
// for (int i = 0; i < 11; i++) {
// String msg = String.format("hello,第%d条信息", i);
// //消息key可以为null,key值影响消息发往哪个分区
// ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(topic, String.valueOf(i), msg);
// //发送
// kafkaProducer.send(producerRecord);
// System.out.println("生产者发送第"+i+"条信息");
// }
// //关闭
// kafkaProducer.close();
//
// }
//
//}

View File

@ -14,6 +14,8 @@
<modules> <modules>
<module>community-security-modules-shop</module> <module>community-security-modules-shop</module>
<module>community-security-modules-system</module> <module>community-security-modules-system</module>
<module>community-security-modules-photo</module>
<module>community-security-modules-es</module>
</modules> </modules>
<properties> <properties>