java高级

java高级

java数据库

配置连接数据库信息
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://192.168.31.162:3306/javagaoji
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#更改数据源druid
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
pom文件
        <!--连接数据库-->
       <!--引入druid数据源-->
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>druid</artifactId>
           <version>1.1.20</version>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jdbc</artifactId>
       </dependency>
       <dependency>
           <groupId>org.mybatis.spring.boot</groupId>
           <artifactId>mybatis-spring-boot-starter</artifactId>
           <version>2.1.3</version>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <scope>runtime</scope>
       </dependency>
实体类
package com.huahua.springbootgaoji.bean;


import java.sql.Date;

/**
* @author wangtianxv
* @create 2020-09-30 9:41
*/

public class User {

   public Integer id;
   public String name;
   public Integer age;
   public String sex;

   public Date birthday;
   public double price;

   public User() {
  }

   public String getSex() {
       return sex;
  }

   public void setSex(String sex) {
       this.sex = sex;
  }

   public Date getBirthday() {
       return birthday;
  }

   public void setBirthday(Date birthday) {
       this.birthday = birthday;
  }

   public double getPrice() {
       return price;
  }

   public void setPrice(double price) {
       this.price = price;
  }

   public User(Integer id, String name, Integer age, String sex, Date birthday, double price) {
       this.id = id;
       this.name = name;
       this.age = age;
       this.sex = sex;
       this.birthday = birthday;
       this.price = price;
  }

   public User(Integer id, String name, Integer age) {
       this.id = id;
       this.name = name;
       this.age = age;
  }

   public Integer getId() {
       return id;
  }

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

   public String getName() {
       return name;
  }

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

   public Integer getAge() {
       return age;
  }

   public void setAge(Integer age) {
       this.age = age;
  }
}

mapper
package com.huahua.springbootgaoji.mapper;

import com.huahua.springbootgaoji.bean.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

/**
* @author wangtianxv
* @create 2020-09-30 9:47
*/
@Component
@Mapper
public interface UserMapper {

   @Select("select * from user where id=#{id}")
   public User getAllUser(Integer id);

   @Options(useGeneratedKeys = true,keyProperty = "id")//确定主键
   @Insert("insert into user(name) values(#{name})")
   public int insertUser(User user);

   @Delete("delete from user where id=#{id}")
   public Integer deleteUser(Integer id);

   @Update("update user set name=#{name} where id=#{id}")
   public int updateUser(User user);
}
service
package com.huahua.springbootgaoji.service;

import com.huahua.springbootgaoji.bean.User;
import com.huahua.springbootgaoji.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
* @author wangtianxv
* @create 2020-09-30 14:23
*/
@Service
public class UserService {

   @Autowired
   UserMapper userMapper;

   public User getAllUser(@PathVariable("id") Integer id){
       User allUser = userMapper.getAllUser(id);
       System.out.println("查询"+id+"员工");
       return allUser;
  }

   public  User insertUser( User user){
       userMapper.insertUser(user);
       System.out.println("添加员工");
       return user;
  }

   public Integer delUser(@PathVariable("id")  Integer id){
       System.out.println("删除"+id+"员工");
       userMapper.deleteUser(id);
       return id;
  }

   public User updepartment(User user){
       userMapper.updateUser(user);
       System.out.println("修改"+user.getId()+"员工");
       User allUser = userMapper.getAllUser(user.getId());
       return allUser;
  }
}
controller
package com.huahua.springbootgaoji.controller;

import com.huahua.springbootgaoji.bean.User;
import com.huahua.springbootgaoji.mapper.UserMapper;
import com.huahua.springbootgaoji.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.text.SimpleDateFormat;

/**
* @author wangtianxv
* @create 2020-09-30 9:25
*/
@RestController
public class HelloController {

   @Autowired
   UserService userService;

   @GetMapping("/user/{id}")
   public User getAllUser(@PathVariable("id") Integer id ){
       User allUser = userService.getAllUser(id);
       return allUser;
  }

   @GetMapping("/inuser")
   public  User insertUser( User user){
       userService.insertUser(user);
       return user;
  }
   @GetMapping("/deluser/{id}")
   public Integer delUser(@PathVariable("id")  Integer id){
       userService.delUser(id);
       return id;
  }
   //   http://localhost:8080/update?id=3&&departmentName=%E2%80%9Csss%E2%80%9D
   @GetMapping("upuser")
   public User updepartment(User user){
       userService.updepartment(user);
       User allUser = userService.getAllUser(user.getId());
       return allUser;
  }
}
run
package com.huahua.springbootgaoji;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;

@MapperScan("com.huahua.springbootgaoji.mapper")
@SpringBootApplication
@EnableCaching//开启缓存注解
public class SpringbootGaojiApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootGaojiApplication.class, args);
  }

}

缓存

SpringbootGaojiApplication上加入@EnableCaching注解//开启缓存注解

cache

@EnableCaching 主类配置 表示可以使用cache注解缓存

 

image-20201006101732566

 

package com.huahua.springbootcache.service;

import com.huahua.springbootcache.bean.Employee;
import com.huahua.springbootcache.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
* @author huahua
* @date 2020/9/2 -11:06
*/
@CacheConfig(cacheNames = "emp")//抽取缓存公共配置
@Service
public class EmployeeService {

   @Autowired
   EmployeeMapper employeeMapper;

   @Autowired
   RedisTemplate<Object,Employee> employeeRedisTemplate;

   //查询
   //默认key的值是参数   condition:指定缓存条件 unless:否定缓存(当结果为true,返回值不被缓存),sync缓存是否使用异步
   //cacheNames = "emp" ,key = "#id",condition = "#id>0",unless = "#id>0",sync = true
   @Cacheable(cacheNames = "emp")
   public Employee getEmpById(Integer id) {
       System.out.println("查询"+id+"号员工");
       Employee emp = employeeMapper.getEmpById(id);
       return emp;
  }

   //修改 先运行方法,再把返回值存入缓存中
   @CachePut(value = "emp" , key = "#employee.id")
   public  Employee upEmp(Employee employee){
       System.out.println("upemp"+employee);
           employeeMapper.upEmp(employee);
       return employee;
  }
   //删除 (beforeInvocation = true 清除缓存在方法执行前)
   @CacheEvict(value = "emp",key = "#id" ,beforeInvocation = true /*,allEntries = true 删除所有缓存*/)
   public void delemp(Integer id){
       System.out.println("del"+id);
       employeeMapper.delEmpById(id);
  }
   //指定复杂的缓存规则   put原因 根据lastName查询元素 还是会去数据库查询
//   @Caching(
//           cacheable = {
//                   @Cacheable(value="emp",key = "#lastName")
//           },
//           put = {
//                   @CachePut(value = "emp",key = "#result.id"),
//                   @CachePut(value = "emp",key = "#result.email")
//           }
//   )
   public Employee GetEmpByLastName(String lastName){
       System.out.println("根据lastName查询数据"+lastName);
       Employee employee = employeeMapper.GetEmpByLastName(lastName);
       //redisTemplate.opsForValue().set("emp-01","emp");
       employeeRedisTemplate.opsForValue().set("empwangtainx",employee);
       return employee;
  }
}
config redis配置
package com.huahua.springbootcache.config;

import com.huahua.springbootcache.bean.Department;
import com.huahua.springbootcache.bean.Employee;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.net.JarURLConnection;
import java.net.UnknownHostException;
import java.time.Duration;

/**
 * @author huahua
 * @date 2020/9/3 -14:58
 */
//redis缓存对象时,修改默认的序列化对象

@Configuration
@EnableCaching
public class MyRedisConfig {


 

    //过期时间1天
    private Duration timeToLive = Duration.ofDays(1);
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //默认1
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        System.out.println("log.debug(\"自定义RedisCacheManager加载完成\");");
        return redisCacheManager;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        System.out.println("log.debug(\"自定义RedisTemplate加载完成\");");
        return redisTemplate;
    }
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}
安装连接redis客户端

 

1、宝塔安装redis和php安装扩展redis服务

修改配置文件

image-20201006180337766

即可成功连接redis客户端

2、引入redis-starter

 <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

3、配置redis

spring.redis.host=192.168.31.162

4、使用redis缓存配置序列化

package com.huahua.springbootgaoji.config;

import com.huahua.springbootgaoji.bean.User;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.net.UnknownHostException;
import java.time.Duration;

/**
 * @author huahua
 * @date 2020/9/3 -14:58
 */
//redis缓存对象时,修改默认的序列化对象

@Configuration
@EnableCaching
public class MyRedisConfig {


    //序列化

    //过期时间1天
    private Duration timeToLive = Duration.ofDays(1);
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //默认1
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        System.out.println("log.debug(\"自定义RedisCacheManager加载完成\");");
        return redisCacheManager;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        System.out.println("log.debug(\"自定义RedisTemplate加载完成\");");
        return redisTemplate;
    }
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }
}

5、测试

package com.huahua.springbootgaoji;

import com.huahua.springbootgaoji.bean.User;
import com.huahua.springbootgaoji.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class SpringbootGaojiApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;//专门操作字符串的

    @Autowired
    RedisTemplate redisTemplate;//k,v都是字符串的

    @Autowired
    RedisTemplate<Object,User> userRedisTemplate;


    /*
    redis常见数据类型
    String(字符串),list(列表),set(集合),hash(散列),zset(有序集合)
    stringRedisTemplate.opsForValue()
    stringRedisTemplate.opsForList()
    stringRedisTemplate.opsForSet()
    stringRedisTemplate.opsForHash()
    stringRedisTemplate.opsForZSet()
     */
    @Test
    public  void  testredis(){
        stringRedisTemplate.opsForValue().append("huahua","zhenshuai");
        String huahua = stringRedisTemplate.opsForValue().get("huahua");
        System.out.println(huahua);
//    stringRedisTemplate.opsForList();
//    stringRedisTemplate.opsForSet();
//    stringRedisTemplate.opsForHash();
//    stringRedisTemplate.opsForZSet();
    }

    @Test
    public void t1(){
        User allUser = userMapper.getAllUser(1);
        redisTemplate.opsForValue().set("allUser-01",allUser);

        userRedisTemplate.opsForValue().set("allUser-02",allUser);

        System.out.println(allUser.getId()+allUser.getName()+allUser.getAge()+allUser.getBirthday()+allUser.getPrice());

    }

    @Test
    void contextLoads() {
    }

}

消息RabbitMQ

1、安装rabbitmq
下载rabbitmq镜像
# docker pull rabbitmq:3.8.9-management
开放端口
firewall-cmd --zone=public --add-port=5672/tcp --permanent
firewall-cmd --zone=public --add-port=15672/tcp --permanent
firewall-cmd --reload
firewall-cmd --zone=public --query-port=5672/tcp
firewall-cmd --zone=public --query-port=15672/tcp
运行rabbitmq镜像
docker run -d -p 5672:5672 -p 15672:15672 --name myrabbitmq 镜像id
#修改docker0网络
#停止docker
systemctl stop docker
#docker0
ip link set dev docker0 down
#删除docker0网桥
brctl delbr docker0
#增加docker0 网桥
brctl addbr docker0
#增加网卡
ip addr add 172.18.0.0/16 dev docker0
#启用网卡
ip link set dev docker0 up
#重启docker服务
systemctl restart docker
重启容器
#docker start b336e01aa917

192.168.31.162:15672

成功安装rabbitmq

username:guest

password:guest

image-20201007144458623

 

2、添加交换器

image-20201007145238631

image-20201007145340224

3、添加消息队列

image-20201007145656421

成功创建消息队列

image-20201007145933654

4、交换器绑定消息队列

点击交换机绑定消息队列

direct:点对点发送(根据路由键点对点发送到消息队列)

fanout:都发送消息队列(所有的消息队列都可以收到消息)

topic:根据符合条件的路由键接受消息

 

image-20201007150845424

 

成功绑定消息队列(bindings)

image-20201007151111962

 

image-20201007151525915

 

根据路由键发送消息

image-20201007152030750

绑定路由键的消息队列收到消息

点击消息队列

image-20201007152444341

 

4、引入Spring-boot-starter-amqp
 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
5、配置application.properties
#配置rabbitmq
spring.rabbitmq.host=192.168.31.162
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

RabbitTemplate:给rabbitmq接收和发送消息

AmqpAdmin:RabbitMQ系统管理组件,创建消息队列 交换器

代码
注解形式

① @EnableRabbit //开启基于注解的rabbitmq

② @RabbitListener(queues = "huahua.news") //监听对应消息队列 只要消息队列有内容 就会被调用

接收消息

    @RabbitListener(queues = "huahua.news")//监听对应消息队列  只要消息队列有内容  就会被调用
    public void receive(Object book){
        System.out.println("收到消息book"+ book.toString());
    }

    @RabbitListener(queues = "huahua")
    public void receive01(Message message){
       System.out.println("message"+message.getBody());//获取消息头信息
        System.out.println("message"+message.getMessageProperties());//获取消息对象
   }
测试
	
    @Autowired
    RabbitTemplate rabbitTemplate;

 

@Test
//点对点传数据
    void contextLoads() {

        Map<String, Object> map = new HashMap<>();
        map.put("msg", "第n个消息数据");
        map.put("data", Arrays.asList("huahau", 123, true));
        //      交换机:  "exchange.direct",  路由键: "huahua.news", 值 :map
        //对象被默认序列化之后发送到对应路由键的消息队列中
        User user = new User();
        user.setName("lgz");
        user.setAge(21);
        user.setId(4);
        user.setPrice(32.1);
        rabbitTemplate.convertAndSend("exchange.direct", "huahua.news", user);
    }

    @Test//获取数据
    public void receive() {
        //接收路由键(huahua.news)  接受消息
        Object o = rabbitTemplate.receiveAndConvert("huahua.news");
        //强转获取的对象为user
        User user = (User)rabbitTemplate.receiveAndConvert("huahua.news");
        System.out.println("2111" +user.getName());
    }

    @Test//广播多穿数据
    public void sendfanout() {
        Map<Object, Object> map = new HashMap<>();
        map.put("msg", "旭哥无敌");
        map.put("huahua", Arrays.asList("hauhau", 5214, "caocao", true));
        rabbitTemplate.convertAndSend("exchange.fanout", "", map);
    }
创建消息队列 路由键 绑定规则
    @Autowired
    AmqpAdmin amqpAdmin;//系统管理组件
    
    
    
    // 创建消息队列
    @Test
    public void createEcChange(){
         //创建路由器
        amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
        System.out.println("创建成功");
        //创建消息队列
        amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
        //创建绑定规则
        //  "amqpadmin.queue", Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.hh",null
        //  目的地  ,类型,路由器,路由键,map值
        Map<String, Object> map = new HashMap<>();
        map.put("msg","自定义的路由器,消息队列,路由键,第n个消息数据");
        amqpAdmin.declareBinding(new Binding("amqpadmin.queue", 			       Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.hh",map));
    }
    
@Test//点对点传数据
    void contextLoads() {

        Map<String, Object> map = new HashMap<>();
        map.put("msg", "第n个消息数据");
        map.put("data", Arrays.asList("huahau", 123, true));
        //      交换机:  "exchange.direct",  路由键: "huahua.news", 值 :map
        //对象被默认序列化之后发送到对应路由键的消息队列中
        User user = new User();
        user.setName("小傻子");
        user.setAge(21);
        user.setId(5);
        user.setPrice(32.1);
        rabbitTemplate.convertAndSend("amqpadmin.exchange", "amqp.hh", user);
    }
    

索引elasticsearch

 

elasticsearch clients 官方文档

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

默认使用 REST风格

image-20201009092012831

 

安装elasticsearch

参考:https://blog.csdn.net/qq_28834355/article/details/108014347

保障版本一致

image-20201009101000995

 

docker安装elasticsearch
下载镜像
docker search elasticsearch:7.6.1
docker pull elasticsearch:7.6.1
暴露9200 9300端口
systemctl start firewalld.service
firewall-cmd --zone=public --add-port=9300/tcp --permanent
firewall-cmd --reload
firewall-cmd --zone=public --query-port=9300/tcp
运行镜像生成容器
# docker run -e ES_JAVA_OPTS="-Xms256m -Xms256m" -d -p 9200:9200 -p 9300:9300 --name ES01   5acf0e8da90b
# docker run -d --name es -p 9200:9200 -p 9300:9300 -e ES_JAVA_OPTS="-Xms256m -Xms256m"  -e "discovery.type=single-node" elasticsearch:7.6.1
#修改docker0网络
#停止docker
systemctl stop docker
#docker0
ip link set dev docker0 down
#删除docker0网桥
brctl delbr docker0
#增加docker0 网桥
brctl addbr docker0
#增加网卡
ip addr add 172.18.0.1/16 dev docker0
#启用网卡
ip link set dev docker0 up
#重启docker服务
systemctl restart docker
重启容器
#docker start b336e01aa917

访问:http://192.168.31.162:9200/

成功

 

image-20201008113508935

 

elasticsearch中文官方文档

https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

es: 192.168.31.111:9200
kibana: 192.168.31.111:5601
es-head: 192.168.31.111:9100

es和es-head:可视化界面安装参考 https://blog.csdn.net/qq_28834355/article/details/108014347

kibana安装参考:https://blog.csdn.net/qq_28834355/article/details/108027761

创建索引 发送请求put

 

image-20201008145442932

 

 

 

image-20201008145409813

 

获取索引get

 

image-20201008150033962

 

检查是否有这个索引 head

查看状态码 200 ok 404 found找不到索引

image-20201008150243894

 

删除索引delete

image-20201008150821746

 

获取所有索引 发GET'请求

image-20201008151144423

 

使用kibana操作es

image-20201010180013275

 

es介绍:索引相当于数据库

es核心概念: 面向文档

mysql elasticsearch

数据库database 索引index

表tables type

行rows (数据文档)documents

字段columns fields

索引

字段类型mapping

(分片)倒排索引:关闭无关索引

配置elasticsearch继承SpingBoot

注意 elasticsearch版本一致

引入pom文件

		  <!--引入elasticsearch-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <!--引入fastjson  将对象转化为json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.74</version>
        </dependency>

        <!--thymeleaf解析页面-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--解析网页jsoup    tika  解析电影-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.13.1</version>
        </dependency>

配置application.properties文件


配置类
@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.31.111", 9200, "http")));
                       // new HttpHost("localhost", 9201, "http")));  集群时使用
        return client;
    }
}
test
 //ealsticsearch7.6.1

    //创建索引
    @Test
    void testCreateIndex() throws IOException {
        //1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("wang");
        //2、客户端执行请求indices  请求后获取响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }

    //获取索引   只能判断其是否存在
    @Test
    void Getindex() throws IOException {
        // 创建获取索引请求
        GetIndexRequest request = new GetIndexRequest("wang");
        //客户端执行请求indices  请求获取后响应
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
    //删除索引
    @Test
    void DeleteIndex() throws IOException {
        //创建删除索引
        DeleteIndexRequest request = new DeleteIndexRequest("wang");
        //客户端执行请求   请求获取后响应
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }


    //文档操作
    // 添加文档
    @Test
    void addDocument() throws IOException {
        //创建对象
        User user = new User(2,"huahua",21);
        //创建请求  连接索引
        IndexRequest request = new IndexRequest("wang");
        //put     index/doc/1  设置请求规则
        request.id("1");
//      request.timeout("1s");设置有效时间
        //将我们的数据放入请求   转化为json数据格式
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //客户端发送请求 获取响应的结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(request.toString());
    }
    //获取文档 get  /index/doc/id
    @Test
    void getDocument() throws IOException {
        GetRequest request = new GetRequest("wang","1");

        //不获取_search的上下文
        request.fetchSourceContext(new FetchSourceContext(false));
        //不过滤文档值
        request.storedFields("_none_");
        //判断是否存在文档
        if (restHighLevelClient.exists(request, RequestOptions.DEFAULT)){
            GetRequest getrequest = new GetRequest("wang","1");
            GetResponse getresponse = restHighLevelClient.get(getrequest, RequestOptions.DEFAULT);
            System.out.println(getresponse.getSourceAsString());
        }else {
            User user = new User(2,"huahua",21);
            //创建请求  连接索引
            IndexRequest addrequest = new IndexRequest("wang");
            //put     index/doc/1  设置请求规则
            request.id("1");
//      request.timeout("1s");设置有效时间 超过一秒中不执行
            //将我们的数据放入请求   转化为json数据格式
            addrequest.source(JSON.toJSONString(user), XContentType.JSON);
            //客户端发送请求 获取响应的结果
            IndexResponse response = restHighLevelClient.index(addrequest, RequestOptions.DEFAULT);
        }
    }

    //更新文档
    @Test
    void  updateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("wang","1");

//        updateRequest.timeout("1s");
        User user = new User(2, "lgz", 21);
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
    }
    //删除文档
    @Test
    void deleteDocment() throws IOException {
        DeleteRequest request = new DeleteRequest("wang","1");
//        request.timeout("1s");//设置1s过期
        DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse);
    }

    //批量插入数据
    @Test
    void bulkindex() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.timeout("10s");
        ArrayList<User> arrayList = new ArrayList<>();
        arrayList.add(new User(1, "zhazha", 21));
        arrayList.add(new User(2, "zhenzhen", 21));
        arrayList.add(new User(3, "huahau", 21));
        arrayList.add(new User(4, "zhangsan", 21));
        arrayList.add(new User(5, "lisi", 21));
        //批量操作
        for (int i = 0; i <arrayList.size() ; i++) {
            //批量添加  修改 删除 查看就在此处修改
            bulkRequest.add(
                    new IndexRequest("dada")
                            .id(""+(i+1))
                            .source(JSON.toJSONString(arrayList.get(i)),XContentType.JSON));
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse);
        System.out.println(bulkResponse.hasFailures());//判断是否失败
    }

    //查询索引
    //searchRequest               搜索请求
    //searchSourceBuilder         条件构造
    //HighlightBuilder            构建高亮
    //matchAllQueryBuilder        精确构造
    //******querybuilder          搜索条件对应命令
    @Test
    void search() throws IOException {
        //定义搜索请求
        SearchRequest searchRequest = new SearchRequest(ESconf.ES_INDEX);
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //查询条件 查询构建器

        //QueryBuilders.termQuery 精确查询
//        QueryBuilders.matchAllQuery()  查询所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhenzhen");//精准查询
//        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();//查询所有
       searchSourceBuilder.highlighter();//查询结果高亮

        // 分页
        searchSourceBuilder.from();
        searchSourceBuilder.size();

        //将条件构建器构建入搜索条件
        searchSourceBuilder.query(termQueryBuilder);

        //完成定义的搜索请求
        searchRequest.source(searchSourceBuilder);

        //响应
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //将searchResponce响应结果转化为json
        System.out.println(JSON.toJSONString(searchResponse.getHits()));

        //遍历对象
        System.out.println("===========================");
        for (SearchHit searchHit : searchResponse.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsMap());//将遍历的对象转化为map集合
        }
    }

异步

 

@Service
public class AsyncService {

    @Async//标注异步方法
    public void Async() throws InterruptedException {
        Thread.sleep(3000);//此方法在三秒后执行
        System.out.println("请求被处理");
    }

}

 

@MapperScan("com.huahua.springbootgaoji.mapper")
@SpringBootApplication
@EnableCaching//开启缓存注解
@EnableRabbit//开启基于注解的rabbitmq
@EnableAsync//开启异步任务的注解
public class SpringbootGaojiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootGaojiApplication.class, args);
    }

}

 

@RestController
public class AsyncController {


    @Autowired
    AsyncService asyncService;


    @GetMapping("/async")
    public String async() throws InterruptedException {
        asyncService.Async();
        return "hello async success";
    }
}

 

定时

//定时任务  cron = "秒 分 时 日 月 周几"
    @Scheduled(cron = "0 * * * * MON-SAT")
    public void Scheduled(){
        System.out.println("执行定时任务");
    }
@EnableScheduling //开启定时任务
public class SpringbootGaojiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootGaojiApplication.class, args);
    }

}

image-20201014103908418

 

邮件

<!--引入邮件依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

 

#配置发邮箱的用户名 密码
spring.mail.username=2775006235@qq.com
spring.mail.password=qbqqvnxgzcwidgfj
spring.mail.host=smtp.qq.com

 

 

安全

登录认证

权限控制

分布式

 

 

热部署

监管

posted @   大旭4521  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示