[黑马程序员SpringBoot2]——开发实用篇2

news2024/9/22 4:36:38

目录:

  1. Mongodb简介
  2. Mongodb下载与安装
  3. Mongodb基础操作
  4. Sprintboot整合Mongodb
  5. ES简介
  6. ES下载与安装
  7. ES索引操作
  8. ES文档操作
  9. SpringBoot整合ES客户端操作
  10. 添加文档
  11. 查询文档
  12. 缓存的作用
  13. Spring缓存使用方式
  14. 手机验证码案例-生成验证码
  15. 手机验证码案例-验证码校验
  16. 变更缓存供应商Ehcache
  17. 数据淘汰策略
  18. 变更缓存供应商Redis
  19. memcached下载与安装
  20. 变更缓存供应商memcached

1.Mongodb简介

Mongodb

  • MongoDB是一个开源、高性能、无模式的文档型数据库。NoSQL数据库产品中的一种,是最像关系型数据库的非关系型数据库

淘宝用户数据

  • 存储位置:数据库
  • 特征:永久性存储,修改频度极低

游戏装备数据、游戏道具数据

  • 存储位置:数据库、Mongodb.
  • 特征:永久性存储与临时存储相结合、修改频度较高

直播数据、打赏数据、粉丝数据

  • 存储位置:数据库、Mongadb.
  • 特征:永久性存储与临时存储相结合,修改频度极高

物联网数据

  • 存储位置:Mongadb.
  • 特征:临时存储,修改频度飞速

其他数据...... 

2.Mongodb下载与安装

  • Windows版Mongo下载
    • https:/www.mongodb.com/try/download
  • Windows版Mongo安装
    • 解压缩后设置数据目录
  • Windows版Mongo启动

服务端启动

mongod --dbpath=. . \dataldb.

客户端启动

mongo --host=127.0.0.1 --port=27017

3.Mongodb基础操作

新增


修改


删除

4.Sprintboot整合Mongodb

导入Mongodb驱动

配置客户端

客户端读写Mongodb

Springboot17MongodbApplicationTest.class

package com.example.sprintboot_17_mongodb;

import com.example.sprintboot_17_mongodb.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.List;

@SpringBootTest
class Sprintboot17MongodbApplicationTests {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    void contextLoads() {
        Book book = new Book();
        book.setId(1);
        book.setName("sprintboot");
        book.setType("sprintboot");
        book.setDesctiption("sprintboot");
        mongoTemplate.save(book);
    }

    @Test
    void find() {
        List<Book> all = mongoTemplate.findAll(Book.class);
        System.out.println(all);
    }
    
}

Book.class

package com.example.sprintboot_17_mongodb.domain;

import lombok.Data;

@Data
public class Book {
    private int id;
    private String name;
    private String type;
    private String desctiption;
}

applicaiton.yml

spring:
  data:
    mongodb:
      uri: mongodb://localhost/itheima

5.ES简介

Elasticsearch是一个分布式全文搜索引擎

 

6.ES下载与安装

Windows版ES下载

  • https://www.elastic.co/cn/downloads/elasticsearch

Windows版ES安装与启动 

7.ES索引操作

创建/查询/删除索引

IK分词器

  • 下载: https://github.com/medcl/elasticsearch-analysis-ik/releases

 创建索引并指定规则

8.ES文档操作 

创建文档

查询文档

条件查询

册除文档

修改文档(全量修改)

修改文档(部分修改)

 

9.SpringBoot整合ES客户端操作

导入坐标

配置

客户端

SpringBoat平台并没有跟随ES的更新速度进行同步更新,ES提供了High Level Client操作ES 

导入坐标

客户端

客户端改进

application.yml

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3308/test_db
      username: root
      password: 666666
#  elasticsearch:
#    rest:
#      uris: http://localhost:9200

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Book.class

package com.example.sprintboot_18_es.domain;

import lombok.Data;

@Data
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

 BookDao.interfacer

package com.example.sprintboot_18_es.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.sprintboot_18_es.domain.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BookDao extends BaseMapper<Book> {

}

Sprintboot18EsApplicationTests.class

package com.example.sprintboot_18_es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class Sprintboot18EsApplicationTests {

//    @Autowired
//    private BookDao bookDao;
//
//    @Test
//    void contextLoads() {
//        bookDao.selectById(1);
//    }


//    @Autowired
//    private ElasticsearchRestTemplate template;

    @BeforeEach
    void setUp() {
        HttpHost host = HttpHost.create("http://localhost:9200");
        RestClientBuilder builder = RestClient.builder(host);
        client = new RestHighLevelClient(builder);
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }


    private RestHighLevelClient client;

//    @Test
//    void testCreateClient() throws IOException {
//        HttpHost host = HttpHost.create("http://localhost:9200");
//        RestClientBuilder builder = RestClient.builder(host);
//        client = new RestHighLevelClient(builder);
//        client.close();
//    }


    @Test
    void testCreateIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        client.indices().create(request, RequestOptions.DEFAULT);
    }
}

10.添加文档 

创建索引

添加文档

批量添加文档

Sprintboot18EsAoolicationTests.class

package com.example.sprintboot_18_es;

import com.alibaba.fastjson.JSON;
import com.example.sprintboot_18_es.dao.BookDao;
import com.example.sprintboot_18_es.domain.Book;
import com.oracle.xmlns.internal.webservices.jaxws_databinding.XmlOneway;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
class Sprintboot18EsApplicationTests {

    @Autowired
    private BookDao bookDao;
//
//    @Test
//    void contextLoads() {
//        bookDao.selectById(1);
//    }


//    @Autowired
//    private ElasticsearchRestTemplate template;

    @BeforeEach
    void setUp() {
        HttpHost host = HttpHost.create("http://localhost:9200");
        RestClientBuilder builder = RestClient.builder(host);
        client = new RestHighLevelClient(builder);
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }


    private RestHighLevelClient client;


//    @Test
//    void testCreateClient() throws IOException {
//        HttpHost host = HttpHost.create("http://localhost:9200");
//        RestClientBuilder builder = RestClient.builder(host);
//        client = new RestHighLevelClient(builder);
//        client.close();
//    }


    @Test
    void testCreateIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testCreateIndexByIK() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        String json = "";
        request.source(json, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testCreateDoc() throws IOException {
        Book book = bookDao.selectById(1);
        IndexRequest request = new IndexRequest("books").id(book.getId().toString());
        String json = JSON.toJSONString(book);
        request.source(json, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }


    @Test
    void testCreateDocAll() throws IOException {
        List<Book> bookList = bookDao.selectList(null);
        BulkRequest bulk = new BulkRequest();

        for (Book book : bookList) {
            IndexRequest request = new IndexRequest("books").id(book.getId().toString());
            String json = JSON.toJSONString(book);
            request.source(json, XContentType.JSON);
            bulk.add(request);
        }

        client.bulk(bulk, RequestOptions.DEFAULT);
    }


}

11.查询文档 

按id查询文档

按条件查询文档

 Sprintboot18EsAoolicationTests.class

package com.example.sprintboot_18_es;

import com.alibaba.fastjson.JSON;
import com.example.sprintboot_18_es.dao.BookDao;
import com.example.sprintboot_18_es.domain.Book;
import com.oracle.xmlns.internal.webservices.jaxws_databinding.XmlOneway;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
class Sprintboot18EsApplicationTests {

    @Autowired
    private BookDao bookDao;
//
//    @Test
//    void contextLoads() {
//        bookDao.selectById(1);
//    }


//    @Autowired
//    private ElasticsearchRestTemplate template;

    @BeforeEach
    void setUp() {
        HttpHost host = HttpHost.create("http://localhost:9200");
        RestClientBuilder builder = RestClient.builder(host);
        client = new RestHighLevelClient(builder);
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }


    private RestHighLevelClient client;


//    @Test
//    void testCreateClient() throws IOException {
//        HttpHost host = HttpHost.create("http://localhost:9200");
//        RestClientBuilder builder = RestClient.builder(host);
//        client = new RestHighLevelClient(builder);
//        client.close();
//    }


    @Test
    void testCreateIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testCreateIndexByIK() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        String json = "";
        request.source(json, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testCreateDoc() throws IOException {
        Book book = bookDao.selectById(1);
        IndexRequest request = new IndexRequest("books").id(book.getId().toString());
        String json = JSON.toJSONString(book);
        request.source(json, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }


    @Test
    void testCreateDocAll() throws IOException {
        List<Book> bookList = bookDao.selectList(null);
        BulkRequest bulk = new BulkRequest();

        for (Book book : bookList) {
            IndexRequest request = new IndexRequest("books").id(book.getId().toString());
            String json = JSON.toJSONString(book);
            request.source(json, XContentType.JSON);
            bulk.add(request);
        }

        client.bulk(bulk, RequestOptions.DEFAULT);
    }

    @Test
    void testGet() throws IOException {
        GetRequest request = new GetRequest("books", "1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        System.out.println(json);
    }

    @Test
    void testSearch() throws IOException {
        SearchRequest request = new SearchRequest("books");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.termQuery("name", "spring"));
        request.source(builder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            System.out.println(source);
            Book book = JSON.parseObject(source, Book.class);
            System.out.println(book);
        }
    }


}

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprintboot_18_es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot_18_es</name>
    <description>sprintboot_18_es</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--        <dependency>-->
        <!--            <groupId>org.springframework.boot</groupId>-->
        <!--            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
        <!--        </dependency>-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

12.缓存的作用

  • 缓存是—种介于数据永久存储介质与数据应用之间的数据临时存储介质
  • 使用缓存可以有效的减少低速数据读取过程的次数(例如磁盘IO),提高系统性能
  • 缓存不仅可以用于提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间

BookController.class

package com.example.sprintboot_19_cache.controller;

import com.example.sprintboot_19_cache.domain.Book;
import com.example.sprintboot_19_cache.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("{id}")
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }

    @PostMapping
    public boolean save(@RequestBody Book book) {
        return bookService.save(book);
    }

    @PutMapping
    public boolean update(@RequestBody Book book) {
        return bookService.update(book);
    }

    @DeleteMapping("{id}")
    public boolean delete(@PathVariable Integer id) {
        return bookService.delete(id);
    }

    @GetMapping
    public List<Book> getAll() {
        return bookService.getAll();
    }
}

MsgController.class

package com.example.sprintboot_19_cache.controller;

import com.example.sprintboot_19_cache.service.MsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    private MsgService msgService;

    @GetMapping("{tele}")
    public String getById(@PathVariable String tele) {
        return msgService.get(tele);
    }

    @PostMapping
    public boolean check(String tele, String code) {
        return msgService.check(tele, code);
    }
}

BookDao.class

package com.example.sprintboot_19_cache.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.sprintboot_19_cache.domain.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BookDao extends BaseMapper<Book> {
}

Book.class

package com.example.sprintboot_19_cache.domain;

import lombok.Data;

@Data
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

BookServiceImpl.class

package com.example.sprintboot_19_cache.service.impl;

import com.example.sprintboot_19_cache.dao.BookDao;
import com.example.sprintboot_19_cache.domain.Book;
import com.example.sprintboot_19_cache.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;


    private HashMap<Integer, Book> cache = new HashMap<Integer, Book>();

    @Override
    public Book getById(Integer id) {
        Book book = cache.get(id);
        if (book == null) {
            Book queryBook = bookDao.selectById(id);
            cache.put(id, queryBook);
            return queryBook;
        }
        return cache.get(id);
    }

    @Override
    public boolean save(Book book) {
        return bookDao.insert(book) > 0;
    }

    @Override
    public boolean update(Book book) {
        return bookDao.updateById(book) > 0;
    }

    @Override
    public boolean delete(Integer id) {
        return bookDao.deleteById(id) > 0;
    }

    @Override
    public List<Book> getAll() {
        return bookDao.selectList(null);
    }
}

MsgServiceImpl.class

package com.example.sprintboot_19_cache.service.impl;

import com.example.sprintboot_19_cache.service.MsgService;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class MsgServiceImpl implements MsgService {

    private HashMap<String, String> cache = new HashMap<String, String>();

    @Override
    public String get(String tele) {
        String code = tele.substring(tele.length() - 6);
        cache.put(tele, code);
        return code;
    }

    @Override
    public boolean check(String tele, String code) {
        String queryCode = cache.get(tele);
        return code.equals(queryCode);
    }
}

BookService.class

package com.example.sprintboot_19_cache.service;

import com.example.sprintboot_19_cache.domain.Book;

import java.util.List;

public interface BookService {
    public boolean save(Book book);

    public Book getById(Integer id);

    public boolean update(Book book);

    public boolean delete(Integer id);

    public List<Book> getAll();
}

MsgService.class

package com.example.sprintboot_19_cache.service;

public interface MsgService {
    public String get(String tele);

    public boolean check(String tele, String code);
}

application.yml

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3308/test_db
      username: root
      password: 666666


mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

server:
  port: 8080

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprintboot_19_cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot_19_cache</name>
    <description>sprintboot_19_cache</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

13.Spring缓存使用方式

  •  SpringBoot提供了缓存技术,方便缓存使用
  • 启用缓存
  • 设置进入缓存的数据
  • 设置读取缓存的数据

 导入缓存技术对应的starter

设置当前操作的结果数据进入缓存

 

springBoot启用缓存的方式

  • @EnableCaching
  • @Cacheable

14.手机验证码案例-生成验证码

  • SpringBoot提供的缓存技术除了提供默认的缓存方案,还可以对其他缓存技术进行整合,统一接口,方便缓存技术的开发与管理
  • Generic
  • JCache
  • Ehcache
  • Hazelcast
  • lnfinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple(默认)
  • memcached

缓存使用案例——手机验证码

需求

  • 输入手机号获取验证码,组织文档以短信形式发送给用户(页面模拟)
  • 输入手机号和验证码验证结果

需求分析

  • 提供controller,传入手机号,业务层通过手机号计算出独有的6位验证码数据,存入缓存后返回此数据
  • 提供controller,传入手机号与验证码,业务层通过手机号从缓存中读取验证码与输入验证码进行比对,返回比对结果 

 开启缓存

业务层接口

  

业务层设置获取验证码操作,并存储缓存,手机号为key,验证码为value

  

15.手机验证码案例-验证码校验

  业务层设置校验验证码操作,校验码通过缓存读取,返回校验结果

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprintboot_19_cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot_19_cache</name>
    <description>sprintboot_19_cache</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 applicaiton.yml

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3308/test_db
      username: root
      password: 666666


mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

server:
  port: 8080

CodeUtils.class

package com.example.sprintboot_19_cache.utils;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class CodeUtils {

    private String[] patch = {"000000", "00000", "0000", "000", "00", "0", ""};

    public String generator(String tele) {
        int hash = tele.hashCode();
        int encryption = 20206666;
        long result = hash ^ encryption;
        long nowTime = System.currentTimeMillis();
        result = result ^ nowTime;
        long code = result % 1000000;
        code = code < 0 ? -code : code;
        String codeStr = code + "";
        int len = codeStr.length();

        return patch[len] + codeStr;
    }


    @Cacheable(value = "smsCode", key = "#tele")
    public String get(String tele) {
        return null;
    }

    public static void main(String[] args) {
        System.out.println(new CodeUtils().generator("15033657967"));
    }
}

SMSCodeService.interface

package com.example.sprintboot_19_cache.service;

import com.example.sprintboot_19_cache.domain.SMSCode;

public interface SMSCodeService {
    public String sendCodeToSMS(String tele);

    public boolean checkCode(SMSCode smsCode);
}

SMSCodeServiceImpl.class 

package com.example.sprintboot_19_cache.service.impl;

import com.example.sprintboot_19_cache.domain.SMSCode;
import com.example.sprintboot_19_cache.service.SMSCodeService;
import com.example.sprintboot_19_cache.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

@Service
public class SMSCodeServiceImpl implements SMSCodeService {

    @Autowired
    private CodeUtils codeUtils;

    @Override
    @CachePut(value = "smsCode", key = "#tele")
    public String sendCodeToSMS(String tele) {
        String code = codeUtils.generator(tele);
        return code;
    }

    @Override
    public boolean checkCode(SMSCode smsCode) {
        String code = smsCode.getCode();
        String cacheCode = codeUtils.get(smsCode.getTele());
        return code.equals(cacheCode);
    }

}

SMSCode.class

package com.example.sprintboot_19_cache.domain;

import lombok.Data;

@Data
public class SMSCode {
    private String tele;
    private String code;
}

SMSCodeController.class

package com.example.sprintboot_19_cache.controller;

import com.example.sprintboot_19_cache.domain.SMSCode;
import com.example.sprintboot_19_cache.service.SMSCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sms")
public class SMSCodeController {

    @Autowired
    private SMSCodeService smsCodeService;

    @GetMapping
    public String getCode(String tele) {
        String code = smsCodeService.sendCodeToSMS(tele);
        return code;
    }

    @PostMapping
    public boolean checkCode(SMSCode smsCode) {
        return smsCodeService.checkCode(smsCode);
    }
}

16.变更缓存供应商Ehcache

 加入Ehcache坐标(缓存供应商实现)

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprintboot_19_cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot_19_cache</name>
    <description>sprintboot_19_cache</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

缓存设定为使用Ehcache

 

applicaiton.yml

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3308/test_db
      username: root
      password: 666666
  cache:
    type: ehcache
    ehcache:
      config: ehcache.xml

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

server:
  port: 8080

 

提供ehcache配置文件ehcache.xml 

 

ehcache.xml 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="F:\ehcache"/>
    <defaultCache
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            timeToIdleSeconds="60"
            timeToLiveSeconds="60"
            memoryStoreEvictionPolicy="LRU"/>

    <cache
            name="smsCode"
            eternal="false"
            diskPersistent="false"
            maxElementsInMemory="1000"
            overflowToDisk="false"
            timeToIdleSeconds="10"
            timeToLiveSeconds="10"
            memoryStoreEvictionPolicy="LRU"/>
</ehcache>

17.数据淘汰策略

 

18.变更缓存供应商Redis

 加入Redis坐标(缓存供应商实现)

 

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sprintboot_19_cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot_19_cache</name>
    <description>sprintboot_19_cache</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

配置Redis服务器,缓存设定为使用Redis.

设置Redis相关配置

applicaiton.yml 

#spring:
#  datasource:
#    druid:
#      driver-class-name: com.mysql.cj.jdbc.Driver
#      url: jdbc:mysql://localhost:3308/test_db
#      username: root
#      password: 666666
#  cache:
#    type: ehcache
#    ehcache:
#      config: ehcache.xml

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

server:
  port: 8080

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3308/test_db
      username: root
      password: 666666
  cache:
    type: redis
    redis:
      time-to-live: 10s
      cache-null-values: false
  #      key-prefix: sms_
  #      use-key-prefix: false

  redis:
    host: localhost
    port: 6379

19.memcached下载与安装

下载memcached

  • 地址: https://www.runoob.com/memcached/window-install-memcached.html 

安装memcached

  • 使用管理员身份运行cmd指令

 

 安装

  • memcached.exe -d install

运行memcached

  • 启动服务 
    • memcached.exe -d start
  • 停止服务
    • memcached.exe -d stop

 

20. 变更缓存供应商memcached

  • memcached客户端选择
    • Memcached client for Java:最早期客户端,稳定可靠,用户群广
    • SpyMemcached:效率更高
    • xmemcached:并发处理更好
  • SpningBoot未提供对memcached的整合,需要使用硬编码方式实现客户端初始化管理

加入Xmemcache坐标(缓存供应商实现)

配置memcached服务器必要属性

创建读取属性配置信息类,加载配置

 创建客户端配置类

配置memcached属性

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1229265.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

逐字节讲解 Redis 持久化(RDB 和 AOF)的文件格式(一)

前言 相信各位对 Redis 的这两种持久化机制都不陌生&#xff0c;简单来说&#xff0c;RDB 就是对数据的全量备份&#xff0c;AOF 则是增量备份&#xff0c;而从 4.0 版本开始引入了混合方式&#xff0c;以 7.2.3 版本为例&#xff0c;会生成三类文件&#xff1a;RDB、AOF 和记…

6.10二叉树的所有路径(LC257-E,不太会)

算法&#xff1a; 前序遍历&#xff1a; 因为要让父节点指向孩子节点&#xff0c;才能输出路径。 递归与回溯相辅相成&#xff0c;只要有递归&#xff0c;就一定有回溯。 举个例子理解一下&#xff1a; 中&#xff1a;先push入1 左&#xff1a;再Push入2 右&#xff1a;再…

Linux系统编程 day03 Makefile、gdb、文件IO

Linux系统编程 day03 Makefile、gdb、文件IO 1. Makefile2. gdb3. 文件IO 1. Makefile Makefile文件中定义了一系列规则来指定哪些文件需要先编译&#xff0c;哪些文件需要后编译&#xff0c;哪些文件需要重新编译&#xff0c;甚至更加复杂的功能操作。Makefile就像一个shell脚…

详解“协方差”与“相关系数”

引言 PCA的目标对象是矩阵&#xff0c;例如&#xff0c;有m个样本&#xff0c;每个样本有n个特征&#xff0c;那么就可以构造成一个样本矩阵&#xff0c;并转换成矩阵的形式。 PCA的最终目的是减少特征的个数&#xff0c;去掉那些不重要的特征&#xff0c;也就是减小矩阵列向量…

【LeetCode:689. 三个无重叠子数组的最大和 | 序列dp+前缀和】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

在回调之间共享数据

可以在 App 中为 UI 组件编写回调函数&#xff0c;以指定用户与其交互时的行为方式。 在具有多个相互依赖的 UI 组件的 App 中&#xff0c;回调函数通常必须访问主 App 函数中定义的数据&#xff0c;或与其他回调函数共享数据。例如&#xff0c;如果创建一个具有列表框的 App&a…

vue 如何实现粘贴复制功能

实现粘贴复制功能 vue 实现粘贴复制功能&#xff0c;也可用于app中h5插件&#xff0c;共四种方法&#xff0c;特别推荐第四种方法&#xff0c;具体还需了解根据需求使用 1. 安装第三方插件方法&#xff08;不推荐&#xff09; 这种方法兼容性很好&#xff0c;如果项目只使用了…

如何自己生成fip.bin在Milkv-duo上跑freertos

前言 &#xff08;1&#xff09;PLCT实验室实习生长期招聘&#xff1a;招聘信息链接 &#xff08;2&#xff09;本来是要跑RT-Thread的&#xff0c;搞了很久&#xff0c;一直没成功。哭死&#xff0c;后面mentor通电话&#xff0c;让我先跑一下freertos试试。有可能是因为RT-Th…

这5款好用的app,能让你生活质量和效率飙升

随着科技的进步和智能手机的普及&#xff0c;不少好用的手机APP出现让我们的生活更加便捷&#xff0c;也提升了我们的生活质量&#xff0c;带给我们不少惊喜。接下来&#xff0c;让我们一起探索这5款实用APP&#xff0c;看看有没有适合你的&#xff01; 1、粉笔 一款专门备考…

全屋智能:鱼很大,但水更深

1990年&#xff0c;作为世界首富的比尔盖茨&#xff0c;已经对智能家居生活有了明确畅想。他花了7年时间&#xff0c;耗资1亿多美元&#xff0c;在美国西雅图的华盛顿湖东岸&#xff0c;建了一座占地6600平方米的湖滨别墅。在这座被命名为“未来之屋”的豪宅里&#xff0c;到处…

暖阳脚本_ 将Agent技术的灵活性引入RPA,清华等发布自动化智能体ProAgent

RPA暖阳脚本 近日&#xff0c;来自清华大学的研究人员联合面壁智能、中国人民大学、MIT、CMU 等机构共同发布了新一代流程自动化范式 “智能体流程自动化” Agentic Process Automation&#xff08;APA&#xff09;&#xff0c;结合大模型智能体帮助人类进行工作流构建&#x…

OTP语音芯片 NV080D在智能空气检测仪的应用

随着人们对健康和环保的关注度不断提高&#xff0c;人们对看不见的家居环境也越来越重视。智能空气检测仪的市场需求也在不断增长中&#xff0c;呈现稳中向好的趋势。智能空气检测仪能够检测室内空气中的PM2.5、甲醛、TVOC等有害物质&#xff0c;同时还可以检测温湿度、空气质量…

亚马逊云科技帮助客户在云中构建具有高可靠性和韧性的应用程序

在一个理想的世界里&#xff0c;一切都非常完美&#xff0c;并且一直都在顺畅运作。早晨的通勤没有交通堵塞&#xff0c;最喜欢的停车位一直空着&#xff0c;一杯温度适宜的饮料&#xff0c;生活一帆风顺&#xff0c;没有任何中断。在需要时&#xff0c;您能得到所需的东西。但…

如何简单挖掘公益SRC?

目录 1、寻找漏洞 1)谷歌语法 2)fofa 2、挖掘漏洞 3、提交报告 第一步&#xff1a;“标题”和“厂商信息”和“所属域名” 第二步&#xff1a;其它内容 第三步&#xff1a;复现步骤 0、IP域名归属证明 1、漏洞页 2、该干啥 3、注入的结果 4、上榜吉时 时间&#x…

多视图聚类的论文阅读(一)

当聚类的方式使用的是某一类预定义好的相似性度量时&#xff0c; 会出现如下情况&#xff1a; 数据聚类方面取得了成功&#xff0c;但它们通常依赖于预定义的相似性度量&#xff0c;而这些度量受原始方法的影响:当输入维数相对较高时&#xff0c;往往是无效的。 1. Deep Mult…

asp.net校园二手交易平台系统VS开发sqlserver数据库web结构c#编程计算机网页

一、源码特点 asp.net校园二手交易平台系统 是一套完善的web设计管理系统&#xff0c;系统采用mvc模式&#xff08;BLLDALENTITY&#xff09;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 vs2010&#xff0c;数据库为sqlserver2008&a…

网络渗透测试(TCP/IP)理论篇

TCP/IP体系 垂直服务&#xff1a;底层为高层服务 TCP/IP体系结构是一个分层的协议体系&#xff0c;由多个层次组成&#xff0c;每个层次都负责不同的功能。以下是TCP/IP体系结构的主要层次&#xff1a; 物理层&#xff08;Physical Layer&#xff09;&#xff1a;该层负责传输…

15篇MyBatis-Plus系列集合篇「值得收藏学习」

历史文章&#xff08;文章累计490&#xff09; 《国内最全的Spring Boot系列之一》 《国内最全的Spring Boot系列之二》 《国内最全的Spring Boot系列之三》 《国内最全的Spring Boot系列之四》 《国内最全的Spring Boot系列之五》 《国内最全的Spring Boot系列之六》 M…

向量数据库——AI时代的基座

1.前言 向量数据库在构建基于大语言模型的行业智能应用中扮演着重要角色。大模型虽然能回答一般性问题&#xff0c;但在垂直领域服务中&#xff0c;其知识深度、准确度和时效性有限。为了解决这一问题&#xff0c;企业可以利用向量数据库结合大模型和自有知识资产&#xff0c;…

金属压块液压打包机比例阀放大器

液压打包机是机电一体化产品&#xff0c;主要由机械系统、液压控制系统、上料系统与动力系统等组成。整个打包过程由压包、回程、提箱、转箱、出包上行、出包下行、接包等辅助时间组成。市场上液压打包机主要分为卧式与立式两种&#xff0c;立式废纸打包机的体积比较小&#xf…