es站内站内搜索笔记(一) Mysql 如何设置字段自动获取当前时间

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

猜你喜欢

转载自www.cnblogs.com/gaogaoyanjiu/p/8410013.html