es站內站內搜索筆記(一)


es站內站內搜索筆記(一)

第一節:

  概述

使用elasticsearch進行網站搜索,es是當下最流行的分布式的搜索引擎及大數據分析的中間件,搜房網的主要功能:強大的搜索框,與百度地圖相結合,實現地圖找房,包括前台模塊和后台模塊。

  elasticsearch + mysql +kafka實現站內搜索引擎

  elasticsearch +nginx實現負載均衡

  elk(elasticsearch +logstach+kibana)實現網站分析流量統計

網站技術:

  springboot+mysql+spring data jpa+spring security

  前段技術:bootstrap+jquery+thymeleaf

  圖片上傳:七牛雲+weUpload

  免注冊登錄:阿里短信

第二節:

  技術選型

mysql+es+session+

   數據庫設計:

用戶表:

房源信息表:

表設計原則:

User表和role表是邏輯上的外鍵,並沒有使用數據庫級別的外鍵,這樣做的好處是在數據量大的時候進行分表分庫時不會受到外鍵的束縛

 

 

 

第三節:

  環境搭建

  jdk1.8+maven+IDEA

ES至少需要搭建三個節點

 

spring data jpa +hibernate

第四節:

  單元測試

1、創建實體對象User

package com.imooc.entity;


import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "user")//映射表名
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//主鍵生成策略,兼容mysql和h2
    private Long id;//id

    private String name;//名稱

    private  String password;//密碼

    private String email;//郵箱

    @Column(name = "phone_number")
    private  String phoneNumber;//電話號碼

    private  int status;//狀態

    @Column(name = "create_time")
    private Date createTime;//創建時間

    @Column(name = "last_login_time")
    private Date lastLoginTime;//登錄時間

    @Column(name ="last_update_time" )
    private Date  lastUpdateTime;//更新時間

    private String avatar;//頭像

    /**
     * Alt+Insert,可以生成構造器/Getter/Setter等
     * @return
     */
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getLastLoginTime() {
        return lastLoginTime;
    }

    public void setLastLoginTime(Date lastLoginTime) {
        this.lastLoginTime = lastLoginTime;
    }

    public Date getLastUpdateTime() {
        return lastUpdateTime;
    }

    public void setLastUpdateTime(Date lastUpdateTime) {
        this.lastUpdateTime = lastUpdateTime;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
}

2、創建jpa操作類UserRepository

package com.imooc.repository;

import com.imooc.entity.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User,Long>{
}

3、創建測試類,將共性代碼抽取為父類

package com.imooc;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@Configuration
@ActiveProfiles("test")// 走test數據庫
public class ApplicationTests {
    

}

4、創建子類測試類繼承ApplicationTests類

package com.imooc.entity;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.imooc.ApplicationTests;
import com.imooc.repository.UserRepository;

/**
 * Created by 瓦力.
 */
public class UserRepositoryTest extends ApplicationTests {
    @Autowired
    private UserRepository userRepository;

    @Test
    public void testFindOne() {
        User user = userRepository.findOne(1L);
        Assert.assertEquals("wali", user.getName());
    }
}

配置h2數據庫

  在xunwu-project\src\test\resources\db\*目錄下創建兩個文件

          

在配置文件application-test.properties中配置如下參數

spring.datasource.driver-class-name=org.h2.Driver
# 內存模式
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql

第五節:

 前端集成

  1、thymeleaf模板引擎,配置文件application-test.properties

# thymeleaf  默認路徑是src/resources/templates
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
# thymeleaf 禁止緩存
spring.thymeleaf.cache=false

  2、java配置

package com.imooc.config;

import org.springframework.beans.BeansException;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

/**
* Created by 瓦力.
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
//@Value("${spring.thymeleaf.cache}")
// private boolean thymeleafCacheEnable = true;

private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

/**
* 靜態資源加載配置
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}

/**
* 模板資源解析器
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.thymeleaf")
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
//templateResolver.setCharacterEncoding("UTF-8");
// templateResolver.setCacheable(thymeleafCacheEnable);
return templateResolver;
}

/**
* Thymeleaf標准方言解釋器
*/
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
// 支持Spring EL表達式
templateEngine.setEnableSpringELCompiler(true);

// 支持SpringSecurity方言
// SpringSecurityDialect securityDialect = new SpringSecurityDialect();
// templateEngine.addDialect(securityDialect);
return templateEngine;
}

/**
* 視圖解析器
*/
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}

/**
* Bean Util
* @return
*/
// @Bean
// public ModelMapper modelMapper() {
// return new ModelMapper();
// }
}

4、創建頁面index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Xunwu</title>
</head>
<body>
Hello world,
<span th:text="${name}"></span>

</body>
</html>

5、創建controller

package com.imooc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

@GetMapping(value = "/")
public String index(Model model) {
model.addAttribute("name","Tom");
model.addAttribute("age","26");

return "index";
}
}

IDEA開發工具中,maven快捷方式啟動

配置跳過單元測試

保存后點擊運行箭頭就可以快速啟動了

注意:運行箭頭下邊的綠色小點是表示存在運行的項目

   maven啟動時必須保證沒有項目已經啟動,否則會啟動失敗,會存在端口占用等問題

 spring-boot-devtools配置:

<!-- SpringBoot自帶熱加載開發工具 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>

IDEA配置

使用快捷鍵shift+ctrl+alt+/ 彈出如下窗口,選擇registry

重啟IDEA

 API結構設計

getter/setter生成快捷鍵  alt+insert

API返回數據的結構標准

 

Mysql 如何設置字段自動獲取當前時間

應用場景:


 

1、在數據表中,要記錄每條數據是什么時候創建的,不需要應用程序去特意記錄,而由數據數據庫獲取當前時間自動記錄創建時間;

2、在數據庫中,要記錄每條數據是什么時候修改的,不需要應用程序去特意記錄,而由數據數據庫獲取當前時間自動記錄修改時間;

實現方式:

1、將字段類型設為  TIMESTAMP 

2、將默認值設為  CURRENT_TIMESTAMP

舉例應用:

1、MySQL 腳本實現用例

--添加CreateTime 設置默認時間 CURRENT_TIMESTAMP 

ALTER TABLE `table_name`
ADD COLUMN  `CreateTime` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間' ;

 

--修改CreateTime 設置默認時間 CURRENT_TIMESTAMP 
ALTER TABLE `table_name`
MODIFY COLUMN  `CreateTime` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間' ;

 

--添加UpdateTime 設置 默認時間 CURRENT_TIMESTAMP   設置更新時間為 ON UPDATE CURRENT_TIMESTAMP 
ALTER TABLE `table_name`
ADD COLUMN `UpdateTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '創建時間' ;

 

--修改 UpdateTime 設置 默認時間 CURRENT_TIMESTAMP   設置更新時間為 ON UPDATE CURRENT_TIMESTAMP 

ALTER TABLE `table_name`
MODIFY COLUMN `UpdateTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '創建時間' ;

2、MySQL工具設置

 

 

總結:


 

1、MySQL自動管理,保持和數據庫時間一致性;

2、簡單高效,不需要應用程序開發支持,MySQL自動完成;

3、MySQL中datetime字段的默認值CURRENT_TIMESTAMP

遇到的問題:

 

今日個導入一sql文件,出現錯誤,指向sql中的datetime字段,查了一下,發現是版本問題

立馬查詢自己的MySQL版本,發現是5.6以下的版本,datetime設置默認為CURRENT_TIMESTAMP時,需要在5.6版本以上才可以,否則,還是老實用:timestamp類型,去設置默認值為當前時間:CURRENT_TIMESTAMP吧

 如果是mysql5.6版本以下的版本:

可以改成這樣:

CREATE TABLE comment_user ( user_account VARCHAR (60), user_name VARCHAR (60), comment_content VARCHAR (500), comment_time TIMESTAMP not NULL DEFAULT CURRENT_TIMESTAMP ); 

 

 

mysl 安裝的有一個問題:

 

rpm -ivh mysql-community-release-el7-5.noarch.rpm

rpm -qa | grep -i mysql

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM