• [黑马程序员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

    1. package com.example.sprintboot_17_mongodb;
    2. import com.example.sprintboot_17_mongodb.domain.Book;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import org.springframework.data.mongodb.core.MongoTemplate;
    7. import java.util.List;
    8. @SpringBootTest
    9. class Sprintboot17MongodbApplicationTests {
    10. @Autowired
    11. private MongoTemplate mongoTemplate;
    12. @Test
    13. void contextLoads() {
    14. Book book = new Book();
    15. book.setId(1);
    16. book.setName("sprintboot");
    17. book.setType("sprintboot");
    18. book.setDesctiption("sprintboot");
    19. mongoTemplate.save(book);
    20. }
    21. @Test
    22. void find() {
    23. List all = mongoTemplate.findAll(Book.class);
    24. System.out.println(all);
    25. }
    26. }

    Book.class

    1. package com.example.sprintboot_17_mongodb.domain;
    2. import lombok.Data;
    3. @Data
    4. public class Book {
    5. private int id;
    6. private String name;
    7. private String type;
    8. private String desctiption;
    9. }

    applicaiton.yml

    1. spring:
    2. data:
    3. mongodb:
    4. uri: mongodb://localhost/itheima

    5.ES简介

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

     

    6.ES下载与安装

    Windows版ES下载

    Windows版ES安装与启动 

    7.ES索引操作

    创建/查询/删除索引

    IK分词器

     创建索引并指定规则

    8.ES文档操作 

    创建文档

    查询文档

    条件查询

    册除文档

    修改文档(全量修改)

    修改文档(部分修改)

     

    9.SpringBoot整合ES客户端操作

    导入坐标

    配置

    客户端

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

    导入坐标

    客户端

    客户端改进

    application.yml

    1. spring:
    2. datasource:
    3. druid:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. url: jdbc:mysql://localhost:3308/test_db
    6. username: root
    7. password: 666666
    8. # elasticsearch:
    9. # rest:
    10. # uris: http://localhost:9200
    11. mybatis-plus:
    12. global-config:
    13. db-config:
    14. table-prefix: tbl_
    15. id-type: auto
    16. configuration:
    17. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

    Book.class

    1. package com.example.sprintboot_18_es.domain;
    2. import lombok.Data;
    3. @Data
    4. public class Book {
    5. private Integer id;
    6. private String type;
    7. private String name;
    8. private String description;
    9. }

     BookDao.interfacer

    1. package com.example.sprintboot_18_es.dao;
    2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    3. import com.example.sprintboot_18_es.domain.Book;
    4. import org.apache.ibatis.annotations.Mapper;
    5. @Mapper
    6. public interface BookDao extends BaseMapper {
    7. }

    Sprintboot18EsApplicationTests.class

    1. package com.example.sprintboot_18_es;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
    4. import org.elasticsearch.client.RequestOptions;
    5. import org.elasticsearch.client.RestClient;
    6. import org.elasticsearch.client.RestClientBuilder;
    7. import org.elasticsearch.client.RestHighLevelClient;
    8. import org.junit.jupiter.api.AfterAll;
    9. import org.junit.jupiter.api.AfterEach;
    10. import org.junit.jupiter.api.BeforeEach;
    11. import org.junit.jupiter.api.Test;
    12. import org.springframework.boot.test.context.SpringBootTest;
    13. import java.io.IOException;
    14. @SpringBootTest
    15. class Sprintboot18EsApplicationTests {
    16. // @Autowired
    17. // private BookDao bookDao;
    18. //
    19. // @Test
    20. // void contextLoads() {
    21. // bookDao.selectById(1);
    22. // }
    23. // @Autowired
    24. // private ElasticsearchRestTemplate template;
    25. @BeforeEach
    26. void setUp() {
    27. HttpHost host = HttpHost.create("http://localhost:9200");
    28. RestClientBuilder builder = RestClient.builder(host);
    29. client = new RestHighLevelClient(builder);
    30. }
    31. @AfterEach
    32. void tearDown() throws IOException {
    33. client.close();
    34. }
    35. private RestHighLevelClient client;
    36. // @Test
    37. // void testCreateClient() throws IOException {
    38. // HttpHost host = HttpHost.create("http://localhost:9200");
    39. // RestClientBuilder builder = RestClient.builder(host);
    40. // client = new RestHighLevelClient(builder);
    41. // client.close();
    42. // }
    43. @Test
    44. void testCreateIndex() throws IOException {
    45. CreateIndexRequest request = new CreateIndexRequest("books");
    46. client.indices().create(request, RequestOptions.DEFAULT);
    47. }
    48. }

    10.添加文档 

    创建索引

    添加文档

    批量添加文档

    Sprintboot18EsAoolicationTests.class

    1. package com.example.sprintboot_18_es;
    2. import com.alibaba.fastjson.JSON;
    3. import com.example.sprintboot_18_es.dao.BookDao;
    4. import com.example.sprintboot_18_es.domain.Book;
    5. import com.oracle.xmlns.internal.webservices.jaxws_databinding.XmlOneway;
    6. import org.apache.http.HttpHost;
    7. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
    8. import org.elasticsearch.action.bulk.BulkRequest;
    9. import org.elasticsearch.action.bulk.BulkResponse;
    10. import org.elasticsearch.action.index.IndexRequest;
    11. import org.elasticsearch.client.RequestOptions;
    12. import org.elasticsearch.client.RestClient;
    13. import org.elasticsearch.client.RestClientBuilder;
    14. import org.elasticsearch.client.RestHighLevelClient;
    15. import org.elasticsearch.common.xcontent.XContentType;
    16. import org.junit.jupiter.api.AfterAll;
    17. import org.junit.jupiter.api.AfterEach;
    18. import org.junit.jupiter.api.BeforeEach;
    19. import org.junit.jupiter.api.Test;
    20. import org.springframework.beans.factory.annotation.Autowired;
    21. import org.springframework.boot.test.context.SpringBootTest;
    22. import java.io.IOException;
    23. import java.util.List;
    24. @SpringBootTest
    25. class Sprintboot18EsApplicationTests {
    26. @Autowired
    27. private BookDao bookDao;
    28. //
    29. // @Test
    30. // void contextLoads() {
    31. // bookDao.selectById(1);
    32. // }
    33. // @Autowired
    34. // private ElasticsearchRestTemplate template;
    35. @BeforeEach
    36. void setUp() {
    37. HttpHost host = HttpHost.create("http://localhost:9200");
    38. RestClientBuilder builder = RestClient.builder(host);
    39. client = new RestHighLevelClient(builder);
    40. }
    41. @AfterEach
    42. void tearDown() throws IOException {
    43. client.close();
    44. }
    45. private RestHighLevelClient client;
    46. // @Test
    47. // void testCreateClient() throws IOException {
    48. // HttpHost host = HttpHost.create("http://localhost:9200");
    49. // RestClientBuilder builder = RestClient.builder(host);
    50. // client = new RestHighLevelClient(builder);
    51. // client.close();
    52. // }
    53. @Test
    54. void testCreateIndex() throws IOException {
    55. CreateIndexRequest request = new CreateIndexRequest("books");
    56. client.indices().create(request, RequestOptions.DEFAULT);
    57. }
    58. @Test
    59. void testCreateIndexByIK() throws IOException {
    60. CreateIndexRequest request = new CreateIndexRequest("books");
    61. String json = "";
    62. request.source(json, XContentType.JSON);
    63. client.indices().create(request, RequestOptions.DEFAULT);
    64. }
    65. @Test
    66. void testCreateDoc() throws IOException {
    67. Book book = bookDao.selectById(1);
    68. IndexRequest request = new IndexRequest("books").id(book.getId().toString());
    69. String json = JSON.toJSONString(book);
    70. request.source(json, XContentType.JSON);
    71. client.index(request, RequestOptions.DEFAULT);
    72. }
    73. @Test
    74. void testCreateDocAll() throws IOException {
    75. List bookList = bookDao.selectList(null);
    76. BulkRequest bulk = new BulkRequest();
    77. for (Book book : bookList) {
    78. IndexRequest request = new IndexRequest("books").id(book.getId().toString());
    79. String json = JSON.toJSONString(book);
    80. request.source(json, XContentType.JSON);
    81. bulk.add(request);
    82. }
    83. client.bulk(bulk, RequestOptions.DEFAULT);
    84. }
    85. }

    11.查询文档 

    按id查询文档

    按条件查询文档

     Sprintboot18EsAoolicationTests.class

    1. package com.example.sprintboot_18_es;
    2. import com.alibaba.fastjson.JSON;
    3. import com.example.sprintboot_18_es.dao.BookDao;
    4. import com.example.sprintboot_18_es.domain.Book;
    5. import com.oracle.xmlns.internal.webservices.jaxws_databinding.XmlOneway;
    6. import org.apache.http.HttpHost;
    7. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
    8. import org.elasticsearch.action.bulk.BulkRequest;
    9. import org.elasticsearch.action.bulk.BulkResponse;
    10. import org.elasticsearch.action.get.GetRequest;
    11. import org.elasticsearch.action.get.GetResponse;
    12. import org.elasticsearch.action.index.IndexRequest;
    13. import org.elasticsearch.action.search.SearchRequest;
    14. import org.elasticsearch.action.search.SearchResponse;
    15. import org.elasticsearch.client.RequestOptions;
    16. import org.elasticsearch.client.RestClient;
    17. import org.elasticsearch.client.RestClientBuilder;
    18. import org.elasticsearch.client.RestHighLevelClient;
    19. import org.elasticsearch.common.xcontent.XContentType;
    20. import org.elasticsearch.index.query.QueryBuilders;
    21. import org.elasticsearch.search.SearchHit;
    22. import org.elasticsearch.search.SearchHits;
    23. import org.elasticsearch.search.builder.SearchSourceBuilder;
    24. import org.junit.jupiter.api.AfterAll;
    25. import org.junit.jupiter.api.AfterEach;
    26. import org.junit.jupiter.api.BeforeEach;
    27. import org.junit.jupiter.api.Test;
    28. import org.springframework.beans.factory.annotation.Autowired;
    29. import org.springframework.boot.test.context.SpringBootTest;
    30. import java.io.IOException;
    31. import java.util.List;
    32. @SpringBootTest
    33. class Sprintboot18EsApplicationTests {
    34. @Autowired
    35. private BookDao bookDao;
    36. //
    37. // @Test
    38. // void contextLoads() {
    39. // bookDao.selectById(1);
    40. // }
    41. // @Autowired
    42. // private ElasticsearchRestTemplate template;
    43. @BeforeEach
    44. void setUp() {
    45. HttpHost host = HttpHost.create("http://localhost:9200");
    46. RestClientBuilder builder = RestClient.builder(host);
    47. client = new RestHighLevelClient(builder);
    48. }
    49. @AfterEach
    50. void tearDown() throws IOException {
    51. client.close();
    52. }
    53. private RestHighLevelClient client;
    54. // @Test
    55. // void testCreateClient() throws IOException {
    56. // HttpHost host = HttpHost.create("http://localhost:9200");
    57. // RestClientBuilder builder = RestClient.builder(host);
    58. // client = new RestHighLevelClient(builder);
    59. // client.close();
    60. // }
    61. @Test
    62. void testCreateIndex() throws IOException {
    63. CreateIndexRequest request = new CreateIndexRequest("books");
    64. client.indices().create(request, RequestOptions.DEFAULT);
    65. }
    66. @Test
    67. void testCreateIndexByIK() throws IOException {
    68. CreateIndexRequest request = new CreateIndexRequest("books");
    69. String json = "";
    70. request.source(json, XContentType.JSON);
    71. client.indices().create(request, RequestOptions.DEFAULT);
    72. }
    73. @Test
    74. void testCreateDoc() throws IOException {
    75. Book book = bookDao.selectById(1);
    76. IndexRequest request = new IndexRequest("books").id(book.getId().toString());
    77. String json = JSON.toJSONString(book);
    78. request.source(json, XContentType.JSON);
    79. client.index(request, RequestOptions.DEFAULT);
    80. }
    81. @Test
    82. void testCreateDocAll() throws IOException {
    83. List bookList = bookDao.selectList(null);
    84. BulkRequest bulk = new BulkRequest();
    85. for (Book book : bookList) {
    86. IndexRequest request = new IndexRequest("books").id(book.getId().toString());
    87. String json = JSON.toJSONString(book);
    88. request.source(json, XContentType.JSON);
    89. bulk.add(request);
    90. }
    91. client.bulk(bulk, RequestOptions.DEFAULT);
    92. }
    93. @Test
    94. void testGet() throws IOException {
    95. GetRequest request = new GetRequest("books", "1");
    96. GetResponse response = client.get(request, RequestOptions.DEFAULT);
    97. String json = response.getSourceAsString();
    98. System.out.println(json);
    99. }
    100. @Test
    101. void testSearch() throws IOException {
    102. SearchRequest request = new SearchRequest("books");
    103. SearchSourceBuilder builder = new SearchSourceBuilder();
    104. builder.query(QueryBuilders.termQuery("name", "spring"));
    105. request.source(builder);
    106. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    107. SearchHits hits = response.getHits();
    108. for (SearchHit hit : hits) {
    109. String source = hit.getSourceAsString();
    110. System.out.println(source);
    111. Book book = JSON.parseObject(source, Book.class);
    112. System.out.println(book);
    113. }
    114. }
    115. }

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.5.4
    8. com.example
    9. sprintboot_18_es
    10. 0.0.1-SNAPSHOT
    11. sprintboot_18_es
    12. sprintboot_18_es
    13. 1.8
    14. org.springframework.boot
    15. spring-boot-starter
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. test
    19. com.baomidou
    20. mybatis-plus-boot-starter
    21. 3.4.1
    22. com.alibaba
    23. druid-spring-boot-starter
    24. 1.2.6
    25. mysql
    26. mysql-connector-java
    27. org.projectlombok
    28. lombok
    29. org.elasticsearch.client
    30. elasticsearch-rest-high-level-client
    31. com.alibaba
    32. fastjson
    33. 1.2.78
    34. org.springframework.boot
    35. spring-boot-maven-plugin
    36. paketobuildpacks/builder-jammy-base:latest

    12.缓存的作用

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

    BookController.class

    1. package com.example.sprintboot_19_cache.controller;
    2. import com.example.sprintboot_19_cache.domain.Book;
    3. import com.example.sprintboot_19_cache.service.BookService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.*;
    6. import java.util.List;
    7. @RestController
    8. @RequestMapping("/books")
    9. public class BookController {
    10. @Autowired
    11. private BookService bookService;
    12. @GetMapping("{id}")
    13. public Book getById(@PathVariable Integer id) {
    14. return bookService.getById(id);
    15. }
    16. @PostMapping
    17. public boolean save(@RequestBody Book book) {
    18. return bookService.save(book);
    19. }
    20. @PutMapping
    21. public boolean update(@RequestBody Book book) {
    22. return bookService.update(book);
    23. }
    24. @DeleteMapping("{id}")
    25. public boolean delete(@PathVariable Integer id) {
    26. return bookService.delete(id);
    27. }
    28. @GetMapping
    29. public List getAll() {
    30. return bookService.getAll();
    31. }
    32. }

    MsgController.class

    1. package com.example.sprintboot_19_cache.controller;
    2. import com.example.sprintboot_19_cache.service.MsgService;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.web.bind.annotation.*;
    5. @RestController
    6. @RequestMapping("/msg")
    7. public class MsgController {
    8. @Autowired
    9. private MsgService msgService;
    10. @GetMapping("{tele}")
    11. public String getById(@PathVariable String tele) {
    12. return msgService.get(tele);
    13. }
    14. @PostMapping
    15. public boolean check(String tele, String code) {
    16. return msgService.check(tele, code);
    17. }
    18. }

    BookDao.class

    1. package com.example.sprintboot_19_cache.dao;
    2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    3. import com.example.sprintboot_19_cache.domain.Book;
    4. import org.apache.ibatis.annotations.Mapper;
    5. @Mapper
    6. public interface BookDao extends BaseMapper {
    7. }

    Book.class

    1. package com.example.sprintboot_19_cache.domain;
    2. import lombok.Data;
    3. @Data
    4. public class Book {
    5. private Integer id;
    6. private String type;
    7. private String name;
    8. private String description;
    9. }

    BookServiceImpl.class

    1. package com.example.sprintboot_19_cache.service.impl;
    2. import com.example.sprintboot_19_cache.dao.BookDao;
    3. import com.example.sprintboot_19_cache.domain.Book;
    4. import com.example.sprintboot_19_cache.service.BookService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.HashMap;
    8. import java.util.List;
    9. @Service
    10. public class BookServiceImpl implements BookService {
    11. @Autowired
    12. private BookDao bookDao;
    13. private HashMap cache = new HashMap();
    14. @Override
    15. public Book getById(Integer id) {
    16. Book book = cache.get(id);
    17. if (book == null) {
    18. Book queryBook = bookDao.selectById(id);
    19. cache.put(id, queryBook);
    20. return queryBook;
    21. }
    22. return cache.get(id);
    23. }
    24. @Override
    25. public boolean save(Book book) {
    26. return bookDao.insert(book) > 0;
    27. }
    28. @Override
    29. public boolean update(Book book) {
    30. return bookDao.updateById(book) > 0;
    31. }
    32. @Override
    33. public boolean delete(Integer id) {
    34. return bookDao.deleteById(id) > 0;
    35. }
    36. @Override
    37. public List getAll() {
    38. return bookDao.selectList(null);
    39. }
    40. }

    MsgServiceImpl.class

    1. package com.example.sprintboot_19_cache.service.impl;
    2. import com.example.sprintboot_19_cache.service.MsgService;
    3. import org.springframework.stereotype.Service;
    4. import java.util.HashMap;
    5. @Service
    6. public class MsgServiceImpl implements MsgService {
    7. private HashMap cache = new HashMap();
    8. @Override
    9. public String get(String tele) {
    10. String code = tele.substring(tele.length() - 6);
    11. cache.put(tele, code);
    12. return code;
    13. }
    14. @Override
    15. public boolean check(String tele, String code) {
    16. String queryCode = cache.get(tele);
    17. return code.equals(queryCode);
    18. }
    19. }

    BookService.class

    1. package com.example.sprintboot_19_cache.service;
    2. import com.example.sprintboot_19_cache.domain.Book;
    3. import java.util.List;
    4. public interface BookService {
    5. public boolean save(Book book);
    6. public Book getById(Integer id);
    7. public boolean update(Book book);
    8. public boolean delete(Integer id);
    9. public List getAll();
    10. }

    MsgService.class

    1. package com.example.sprintboot_19_cache.service;
    2. public interface MsgService {
    3. public String get(String tele);
    4. public boolean check(String tele, String code);
    5. }

    application.yml

    1. spring:
    2. datasource:
    3. druid:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. url: jdbc:mysql://localhost:3308/test_db
    6. username: root
    7. password: 666666
    8. mybatis-plus:
    9. global-config:
    10. db-config:
    11. table-prefix: tbl_
    12. id-type: auto
    13. configuration:
    14. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    15. server:
    16. port: 8080

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.5.4
    8. com.example
    9. sprintboot_19_cache
    10. 0.0.1-SNAPSHOT
    11. sprintboot_19_cache
    12. sprintboot_19_cache
    13. 1.8
    14. org.springframework.boot
    15. spring-boot-starter-web
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. test
    19. org.projectlombok
    20. lombok
    21. com.baomidou
    22. mybatis-plus-boot-starter
    23. 3.4.3
    24. com.alibaba
    25. druid-spring-boot-starter
    26. 1.2.6
    27. mysql
    28. mysql-connector-java
    29. org.springframework.boot
    30. spring-boot-maven-plugin
    31. paketobuildpacks/builder-jammy-base:latest

    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

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.5.4
    8. com.example
    9. sprintboot_19_cache
    10. 0.0.1-SNAPSHOT
    11. sprintboot_19_cache
    12. sprintboot_19_cache
    13. 1.8
    14. org.springframework.boot
    15. spring-boot-starter-web
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. test
    19. org.projectlombok
    20. lombok
    21. com.baomidou
    22. mybatis-plus-boot-starter
    23. 3.4.3
    24. com.alibaba
    25. druid-spring-boot-starter
    26. 1.2.6
    27. mysql
    28. mysql-connector-java
    29. org.springframework.boot
    30. spring-boot-starter-cache
    31. org.springframework.boot
    32. spring-boot-maven-plugin
    33. paketobuildpacks/builder-jammy-base:latest

     applicaiton.yml

    1. spring:
    2. datasource:
    3. druid:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. url: jdbc:mysql://localhost:3308/test_db
    6. username: root
    7. password: 666666
    8. mybatis-plus:
    9. global-config:
    10. db-config:
    11. table-prefix: tbl_
    12. id-type: auto
    13. configuration:
    14. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    15. server:
    16. port: 8080

    CodeUtils.class

    1. package com.example.sprintboot_19_cache.utils;
    2. import org.springframework.cache.annotation.Cacheable;
    3. import org.springframework.stereotype.Component;
    4. @Component
    5. public class CodeUtils {
    6. private String[] patch = {"000000", "00000", "0000", "000", "00", "0", ""};
    7. public String generator(String tele) {
    8. int hash = tele.hashCode();
    9. int encryption = 20206666;
    10. long result = hash ^ encryption;
    11. long nowTime = System.currentTimeMillis();
    12. result = result ^ nowTime;
    13. long code = result % 1000000;
    14. code = code < 0 ? -code : code;
    15. String codeStr = code + "";
    16. int len = codeStr.length();
    17. return patch[len] + codeStr;
    18. }
    19. @Cacheable(value = "smsCode", key = "#tele")
    20. public String get(String tele) {
    21. return null;
    22. }
    23. public static void main(String[] args) {
    24. System.out.println(new CodeUtils().generator("15033657967"));
    25. }
    26. }

    SMSCodeService.interface

    1. package com.example.sprintboot_19_cache.service;
    2. import com.example.sprintboot_19_cache.domain.SMSCode;
    3. public interface SMSCodeService {
    4. public String sendCodeToSMS(String tele);
    5. public boolean checkCode(SMSCode smsCode);
    6. }

    SMSCodeServiceImpl.class 

    1. package com.example.sprintboot_19_cache.service.impl;
    2. import com.example.sprintboot_19_cache.domain.SMSCode;
    3. import com.example.sprintboot_19_cache.service.SMSCodeService;
    4. import com.example.sprintboot_19_cache.utils.CodeUtils;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.cache.annotation.CachePut;
    7. import org.springframework.stereotype.Service;
    8. @Service
    9. public class SMSCodeServiceImpl implements SMSCodeService {
    10. @Autowired
    11. private CodeUtils codeUtils;
    12. @Override
    13. @CachePut(value = "smsCode", key = "#tele")
    14. public String sendCodeToSMS(String tele) {
    15. String code = codeUtils.generator(tele);
    16. return code;
    17. }
    18. @Override
    19. public boolean checkCode(SMSCode smsCode) {
    20. String code = smsCode.getCode();
    21. String cacheCode = codeUtils.get(smsCode.getTele());
    22. return code.equals(cacheCode);
    23. }
    24. }

    SMSCode.class

    1. package com.example.sprintboot_19_cache.domain;
    2. import lombok.Data;
    3. @Data
    4. public class SMSCode {
    5. private String tele;
    6. private String code;
    7. }

    SMSCodeController.class

    1. package com.example.sprintboot_19_cache.controller;
    2. import com.example.sprintboot_19_cache.domain.SMSCode;
    3. import com.example.sprintboot_19_cache.service.SMSCodeService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PostMapping;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. @RestController
    10. @RequestMapping("/sms")
    11. public class SMSCodeController {
    12. @Autowired
    13. private SMSCodeService smsCodeService;
    14. @GetMapping
    15. public String getCode(String tele) {
    16. String code = smsCodeService.sendCodeToSMS(tele);
    17. return code;
    18. }
    19. @PostMapping
    20. public boolean checkCode(SMSCode smsCode) {
    21. return smsCodeService.checkCode(smsCode);
    22. }
    23. }

    16.变更缓存供应商Ehcache

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

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.5.4
    8. com.example
    9. sprintboot_19_cache
    10. 0.0.1-SNAPSHOT
    11. sprintboot_19_cache
    12. sprintboot_19_cache
    13. 1.8
    14. org.springframework.boot
    15. spring-boot-starter-web
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. test
    19. org.projectlombok
    20. lombok
    21. com.baomidou
    22. mybatis-plus-boot-starter
    23. 3.4.3
    24. com.alibaba
    25. druid-spring-boot-starter
    26. 1.2.6
    27. mysql
    28. mysql-connector-java
    29. org.springframework.boot
    30. spring-boot-starter-cache
    31. net.sf.ehcache
    32. ehcache
    33. org.springframework.boot
    34. spring-boot-maven-plugin
    35. paketobuildpacks/builder-jammy-base:latest

     

    缓存设定为使用Ehcache

     

    applicaiton.yml

    1. spring:
    2. datasource:
    3. druid:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. url: jdbc:mysql://localhost:3308/test_db
    6. username: root
    7. password: 666666
    8. cache:
    9. type: ehcache
    10. ehcache:
    11. config: ehcache.xml
    12. mybatis-plus:
    13. global-config:
    14. db-config:
    15. table-prefix: tbl_
    16. id-type: auto
    17. configuration:
    18. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    19. server:
    20. port: 8080

     

    提供ehcache配置文件ehcache.xml 

     

    ehcache.xml 

    1. "1.0" encoding="UTF-8"?>
    2. "http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    4. updateCheck="false">
    5. "F:\ehcache"/>
    6. eternal="false"
    7. diskPersistent="false"
    8. maxElementsInMemory="1000"
    9. overflowToDisk="false"
    10. timeToIdleSeconds="60"
    11. timeToLiveSeconds="60"
    12. memoryStoreEvictionPolicy="LRU"/>
    13. name="smsCode"
    14. eternal="false"
    15. diskPersistent="false"
    16. maxElementsInMemory="1000"
    17. overflowToDisk="false"
    18. timeToIdleSeconds="10"
    19. timeToLiveSeconds="10"
    20. memoryStoreEvictionPolicy="LRU"/>

    17.数据淘汰策略

     

    18.变更缓存供应商Redis

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

     

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.5.4
    8. com.example
    9. sprintboot_19_cache
    10. 0.0.1-SNAPSHOT
    11. sprintboot_19_cache
    12. sprintboot_19_cache
    13. 1.8
    14. org.springframework.boot
    15. spring-boot-starter-web
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. test
    19. org.projectlombok
    20. lombok
    21. com.baomidou
    22. mybatis-plus-boot-starter
    23. 3.4.3
    24. com.alibaba
    25. druid-spring-boot-starter
    26. 1.2.6
    27. mysql
    28. mysql-connector-java
    29. org.springframework.boot
    30. spring-boot-starter-cache
    31. net.sf.ehcache
    32. ehcache
    33. org.springframework.boot
    34. spring-boot-starter-data-redis
    35. org.springframework.boot
    36. spring-boot-maven-plugin
    37. paketobuildpacks/builder-jammy-base:latest

     

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

    设置Redis相关配置

    applicaiton.yml 

    1. #spring:
    2. # datasource:
    3. # druid:
    4. # driver-class-name: com.mysql.cj.jdbc.Driver
    5. # url: jdbc:mysql://localhost:3308/test_db
    6. # username: root
    7. # password: 666666
    8. # cache:
    9. # type: ehcache
    10. # ehcache:
    11. # config: ehcache.xml
    12. mybatis-plus:
    13. global-config:
    14. db-config:
    15. table-prefix: tbl_
    16. id-type: auto
    17. configuration:
    18. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    19. server:
    20. port: 8080
    21. spring:
    22. datasource:
    23. druid:
    24. driver-class-name: com.mysql.cj.jdbc.Driver
    25. url: jdbc:mysql://localhost:3308/test_db
    26. username: root
    27. password: 666666
    28. cache:
    29. type: redis
    30. redis:
    31. time-to-live: 10s
    32. cache-null-values: false
    33. # key-prefix: sms_
    34. # use-key-prefix: false
    35. redis:
    36. host: localhost
    37. 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属性

     

  • 相关阅读:
    【Python入门级】#基础篇#文章目录概览汇总
    jvm 内存结构 ^_^
    「 程序员的理财与风险控制」让财富跟你一起持续成长:增额终身寿
    更简洁的参数校验,使用 SpringBoot Validation 对参数进行校验
    黑盒测试用例设计 - 等价类划分法
    22071.11.28
    AI量化策略会:可以直接上实盘的策略构建方法
    vue 配置绕过跨域问题
    jupyter notebook中查看python版本的解决方案
    No matching version found for zr-map-ol@1.1.19.
  • 原文地址:https://blog.csdn.net/qq_56444564/article/details/134480190