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

目录:

  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.mfbz.cn/a/167057.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

dxva2+ffmpeg硬件解码(Windows)终结发布

《dxva2超低延迟视频播放器》演示demo下载URL&#xff1a; 【免费】dxva2硬解码超低延迟网络本地播放器资源-CSDN文库 本地播放 截图&#xff1a; rtsp播放截图&#xff08;推送内容为本地桌面&#xff0c;所以是这样的&#xff09; OK&#xff0c;进入主题&#xff1a; 前前…

一文看懂:5分钟玩转容器云,彻底化解业务上云烦恼

在高速发展的数字化时代&#xff0c;容器云的作用与日俱增。作为一种新兴的技术趋势&#xff0c;容器云的核心思想是&#xff1a;基于容器化技术&#xff0c;将应用程序及其依赖项封装在独立的容器中&#xff0c;进而实现应用程序与其运行环境的完全隔离&#xff0c;极大简化了…

一文读懂:为什么GPU比CPU更快?

大家好&#xff0c;我是老猫&#xff0c;猫头鹰的猫。 在过去几十年里&#xff0c;GPU变得越来越流行&#xff0c;尤其是最近ChatGPT大火&#xff0c;背后训练大模型的硬件设备GPU达到了一片难求的地步。 你有没有好奇&#xff1a;为什么必须要用GPU&#xff1f;CPU被淘汰了吗…

Polygon Miden VM中的哈希函数对比

1. 引言 在Polygon Miden VM中&#xff0c;使用了多个不同的哈希函数&#xff1a; 1&#xff09;“传统”哈希函数&#xff0c;如BLAKE3&#xff1a;对STARK之外的性能进行了优化。2&#xff09;algebraic哈希函数&#xff0c;如Rescue Prime&#xff1a;对STARK内部优化&…

指针学习(五)

一.函数指针数组 定义&#xff1a;函数指针放进数组中&#xff0c;就叫函数指针数组&#xff0c;准确的说&#xff0c;将一个函数的地址存到⼀个数组中 那这个数组就叫函数指针数组。 int (*pi[5])(int); 解读&#xff1a;pi先和[]结合&#xff0c;因此是数组&#xff0c;加i…

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

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

龙讯旷腾PWmat发PRL:多k点计算的NAMD方法应用于小型超胞与在等效的大型超胞中进行的单个Γ点模拟之间的一致性

文章信息 作者信息&#xff1a;郑帆&#xff0c;汪林望 通信单位&#xff1a;上海科技大学 中国科学院半导体所 背景导读 固态材料中的超快载流子动力学在能源材料、光电子学、传感器和量子材料等领域起着关键作用。随着超快实验技术在固态系统中载流子动力学研究中的快速发…

C++大神之路——环境篇

序 在我还在做后端的时候&#xff0c;当时程序员圈里就有个梗很火&#xff0c;说的是当时几种常用编程语言的鄙视链&#xff1a;做C的鄙视做Java的&#xff0c;做Java的鄙视做C#的&#xff0c;而我很不幸&#xff0c;当时在鄙视链最底层。一开始只是当个笑话听听就算了&#x…

IC卡操作软件支持PN532

IC卡操作软件&#xff0c;在知道卡片密码的情况下&#xff0c;可以对卡片修改数据&#xff0c;格式化清卡&#xff0c;修改UID卡和CUID卡的卡号&#xff0c;锁UFUID卡等 卡片dump文件拖进软件&#xff0c;即可打开文件&#xff0c;编辑修改文件&#xff0c;写卡&#xff0c;就…

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

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

【ArcGIS】批量对栅格图像按要素掩膜提取

要把一张大的栅格图裁成分省或者分县市的栅格集&#xff0c;一般是用ArcGIS里的按掩膜提取。 但是有的时候所要求的栅格集量非常大&#xff0c;所以用代码来做批量掩膜&#xff08;按字段&#xff09;会非常方便。 import arcpy , shutil , os from arcpy import env from ar…

数据资产入表,给企业带来的机遇和挑战

作为推动数字经济发展的核心要素&#xff0c;近年来&#xff0c;数据资源对于企业特别是相关数据企业的价值和作用正日益凸显。 数据资产入表之后&#xff0c;能够为企业经营带来实质性的收益。“随着数据资产的纳入&#xff0c;企业的资产也出现了新标的。在资产负债表中&…

c语言:矩阵交换

题目&#xff1a; 代码和思路&#xff1a; #define _CRT_SECURE_NO_WARNINGS #include<stdio.h>int main() {int n 0;int m 0;int arr[10][10] { 0 }; // 输入行和列scanf("%d%d", &n, &m);int i 0;int j 0;//读取数组for (i 0; i < n; i)…

再见 Excel,你好 Python Spreadsheets!⛵

Excel是大家最常用的数据分析工具之一&#xff0c;借助它可以便捷地完成数据清理、统计计算、数据分析&#xff08;数据透视图&#xff09;和图表呈现等。 但是&#xff01;大家有没有用 Excel 处理过大一些的数据&#xff08;比如几十上百万行的数据表&#xff09;&#xff0…

这些PCB设计错误,依然有很多人再犯

在电子的设计制造中&#xff0c;PCB设计是至关重要的环节&#xff0c;尽管PCB设计的重要性得到了广泛认可&#xff0c;但依然有很多工程师在实践中犯下各种错误&#xff0c;本文凡小亿将盘点一些你没发现过的PCB设计错误&#xff0c;希望对小伙伴们有所帮助。 1、散热走线未能正…

四种方法,全面诊断库存管理的“死角”!

当今企业经营竞争环境的特点是&#xff1a;多品种、小批量、快速降价、产品生命周期短&#xff0c;这其实对企业的库存管理提出了高要求&#xff0c;库存在财务报表里是资产&#xff0c;但滞销&#xff08;或滞用&#xff09;的存货&#xff0c;就是将来要吃掉利润的成本&#…

idea项目中java类名出现带 j 小红点,如何解决?

目录 一、问题描述 二、问题解决方案 1、寻找异常问题 2、解决方案 2.1常规操作方法 2.2 快速操作方法 一、问题描述 一打开idea的java项目&#xff0c;发现所有的文件边上都有带J的大红点 虽然&#xff0c;在 git bash 中进行编译时无异常。 但是视觉上给人的感受就是…

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

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

nginx学习(3)

Nginx 负载均衡 实战案例 实现效果 浏览器地址栏输入地址 http://172.31.0.99/oa/a.html&#xff0c;负载均衡效果&#xff0c;平均 8083 和 8084 端口中 一、配置 1、先创建2个文件夹&#xff0c;并将apache-tomcat-8.5.87解压到tomcat8083和tomcat8084中 &#xff08;或…

这8个Wireshark使用技巧,一看就会!

今天就给你分享8个常用的Wireshark使用技巧&#xff0c;一看就会。如果是处理 HTTP&#xff0c;HTTPS 大家还是用还是用 Fiddler&#xff0c;但如果是其他协议比如 TCP&#xff0c;UDP&#xff0c;还是用wireshark。 今天给你准备了wireshark和Fiddler的安装包给你&#xff0c…
最新文章