1. 程式人生 > >搭建mail服務和OCR服務

搭建mail服務和OCR服務

本案例為個人初次搭建springcloud微服務,不足之處,還請留下評論建議。推薦Spring 官網https://spring.io/projects/spring-cloud

JDK要求1.8或以上版本。

實現eureka註冊服務 首先建立兩個專案,eureka-service和eureka-client。  eureka-server作為eureka的服務端,提供註冊服務,eureka-client作為eureka的客戶端,屬於一個應用,註冊到eureka註冊中心。eureka-service的配置檔案pom.xml如下:

<dependencies>         <!--增加eureka-server的依賴-->         <dependency>             <groupId>org.springframework.cloud</groupId>             <artifactId>spring-cloud-starter-eureka-server</artifactId>         </dependency>     </dependencies>

    <!--依賴管理,用於管理spring-cloud的依賴-->     <dependencyManagement>         <dependencies>             <dependency>                 <groupId>org.springframework.cloud</groupId>                 <artifactId>spring-cloud-starter-parent</artifactId>                 <version>Brixton.SR3</version>                    <type>pom</type>                 <scope>import</scope>             </dependency>         </dependencies>     </dependencyManagement>

啟動類中添加註解 @EnableEurekaServer

@SpringBootApplication //springBoot註解,spring在springBoot基礎之上來構建專案 @EnableEurekaServer //開啟eureka服務 public class EurekaDemoApplication {     public static void main(String[] args) {         SpringApplication.run(EurekaDemoApplication.class, args);     } }

關於eureka-service的配置檔案 applicaiton.yml 或者使用application.properties,兩者格式不同。

server.port=8761 #指定服務埠

eureka.instance.hostname=127.0.0.1 eureka.instance.prefer-ip-address=true eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/ eureka.client.registerWithEureka=false eureka.client.fetchRegistry=false

簡單的eureka-service就寫好了,執行下EurekaServiceApplication.java  訪問:http://localhost:8761/

關於eureks-client 的pom.xml檔案如下

<dependencyManagement>     <dependencies>         <dependency>             <groupId>org.springframework.cloud</groupId>             <artifactId>spring-cloud-starter-parent</artifactId>             <version>Brixton.SR3</version>             <type>pom</type>             <scope>import</scope>         </dependency>     </dependencies>   </dependencyManagement>

  <dependencies>       <dependency>           <groupId>org.springframework.cloud</groupId>           <artifactId>spring-cloud-starter-eureka</artifactId>       </dependency>       <dependency>           <groupId>org.springframework.boot</groupId>           <artifactId>spring-boot-starter-test</artifactId>           <scope>test</scope>       </dependency>   </dependencies> 啟動類中的註解 @EnableDiscoveryClient

@EnableDiscoveryClient            //通過該註解,實現服務發現,註冊 @SpringBootApplication public class EurekaClientApplication {

    public static void main(String[] args) {         SpringApplication.run(EurekaClientApplication.class, args);     } application.properties配置檔案

spring.application.name=OCRApp eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/

好了,現在啟動eureka-client,再次訪問http://localhost:8761,可能需要等一會 

接下來介紹實現ActivityMQ

maven 依賴

<!--activitiMq -->         <!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-core -->         <dependency>             <groupId>org.apache.activemq</groupId>             <artifactId>activemq-core</artifactId>             <version>5.7.0</version>         </dependency>         <dependency>             <groupId>org.apache.activemq</groupId>             <artifactId>activemq-broker</artifactId>             <version>5.10.0</version>         </dependency>         <dependency>             <groupId>org.apache.activemq</groupId>             <artifactId>activemq-client</artifactId>             <version>5.14.0</version>         </dependency>

訊息傳送端

 //連線工廠              ConnectionFactory connectionFactory;              //JMS 客戶端到JMS Provider 的連線                Connection connection;              //一個傳送或接收訊息的執行緒              Session session;              // Destination :訊息的目的地;訊息傳送給誰.                Destination destination;              // MessageProducer:訊息傳送者               MessageProducer messageProducer;              connectionFactory=new 

                 ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,                       "tcp://localhost:61616");

 try {                connection=connectionFactory.createConnection();                connection.start();               session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

              //這裡會自動建立Queue               destination=(Destination) session.createQueue("1queue");               messageProducer=session.createProducer((javax.jms.Destination) destination);               //設定生產者的模式,有兩種可選               //DeliveryMode.PERSISTENT 當activemq關閉的時候,佇列資料將會被儲存               //DeliveryMode.NON_PERSISTENT 當activemq關閉的時候,佇列裡面的資料將會被清空               messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);               //設定訊息過期時間               messageProducer.setTimeToLive(100000);               sendMessage(session, messageProducer);                        // session.commit();               session.close();               connection.close();

            } catch (JMSException e) {               e.printStackTrace();             }

          }

        public static void sendMessage(Session session,MessageProducer producer){

            TextMessage message;             try {               for(int i=0;i<10;i++){               message = session.createTextMessage("from mq的訊息"+i);               producer.send(message);                             try {                 Thread.sleep(20);               } catch (InterruptedException e) {                 e.printStackTrace();               }

              }

            } catch (JMSException e) {

訊息接收端

//連線工廠                   ConnectionFactory connectionFactory;                   //JMS 客戶端到JMS Provider 的連線                     Connection connection;                   //一個傳送或接收訊息的執行緒                   Session session;                   // Destination :訊息的目的地;訊息傳送給誰.                     Destination destination;                   // MessageProducer:訊息消費者                    MessageConsumer consumer;                         connectionFactory=new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,                        "tcp://localhost:61616");                try {                     connection=connectionFactory.createConnection();                 connection.start();                 session=connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);                     destination=(Destination) session.createQueue("1queue");                     consumer=session.createConsumer((javax.jms.Destination) destination);                 while(true){                       TextMessage message=(TextMessage) consumer.receive();                       System.out.println(message.getText());                      message.acknowledge();                     }                      } catch (JMSException e) {                     e.printStackTrace();                   }      

下載mq,建立幾個queues  。可以試著玩玩,很好玩,哈哈

關於實現掃面二維碼的ZXING 

maven依賴

<dependency>             <groupId>com.google.zxing</groupId>             <artifactId>core</artifactId>             <version>3.3.0</version>         </dependency>         <dependency>             <groupId>com.google.zxing</groupId>             <artifactId>javase</artifactId>             <version>3.3.0</version>         </dependency>

生成二維碼客戶端程式碼

// TODO Auto-generated method stub         int width=300;      //圖片的寬度         int height=300;     //圖片的高度         String format="png";    //圖片的格式         String content="";     //內容         /**          * 定義二維碼的引數          */         HashMap hints=new HashMap();         hints.put(EncodeHintType.CHARACTER_SET,"utf-8");    //指定字元編碼為“utf-8”         hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);  //指定二維碼的糾錯等級為中級         hints.put(EncodeHintType.MARGIN, 2);    //設定圖片的邊距

        /**          * 生成二維碼          */         try {             BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);             Path file=new File("C:/DBS/code.png").toPath();             MatrixToImageWriter.writeToPath(bitMatrix, format, file);         } catch (Exception e) {             e.printStackTrace();         }

掃描二維碼 客戶端程式碼

MultiFormatReader formatReader=new MultiFormatReader();             File file=new File("C:/DBS/code.png");             BufferedImage image;             try {                 image = ImageIO.read(file);                 BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer                                         (new BufferedImageLuminanceSource(image)));

                HashMap hints=new HashMap();                 hints.put(EncodeHintType.CHARACTER_SET,"utf-8");    //指定字元編碼為“utf-8”

                Result result=formatReader.decode(binaryBitmap,hints);

                System.out.println("解析結果:"+result.toString());                 System.out.println("二維碼格式:"+result.getBarcodeFormat());                 System.out.println("二維碼文字內容:"+result.getText());             } catch (Exception e) {                 e.printStackTrace();             }

AOP 做簡單的日誌處理

@Pointcut("execution(public * com.example.EliasticsearchDemo.*.*(..))")     public void test(){}          @Before("test()")     public void deBefore(JoinPoint joinPoint) throws Throwable {          ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();               HttpServletRequest request = attributes.getRequest();           System.out.println("------------URL-------------------"+request.getRequestURL().toString());         System.out.println("------------param:-------------------"+request.getParameter("name"));     }     最後,介紹下開源的ocr識別工具tesseract

//圖片處理         try {              BufferedImage bufferedImage = ImageIO.read(new File(URL));              BufferedImage subimage = bufferedImage.getSubimage(arr[0],arr[1],arr[2], arr[3]);              ImageIO.write(subimage, "png", new FileOutputStream(new File(ocrUrl)));         } catch (Exception e) {           // TODO Auto-generated catch block              e.printStackTrace();         }                  //TESSERACT識別         if(!"".equals(ocrUrl)){                          File imageFile = new File(ocrUrl);              ITesseract instance = new Tesseract();                           instance.setDatapath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata");                      // 預設是英文(識別字母和數字),如果要識別中文(數字 + 中文),需要指定語言包                      instance.setLanguage("chi_sim");                      try{                                result = instance.doOCR(imageFile);                     System.out.println(result);                          }catch(TesseractException e){                             System.out.println(e.getMessage());                    }             }

tesseract對純文字的識別率還可以,可以達到70%

好了,就這些。

有很多不足之處,還請留下寶貴意見,共同提高技術。

感謝您的閱讀。