SpringBoot study notes (3)

test

Load test-specific properties

Test environment-specific properties can be set through the properties parameter when starting the test environment

@SpringBootTest(poperties = {
    
    "test.prop=testValue1"})
public class PropertiesAndArgsTest {
    
    
	@Value("${test.prop}")
	private String msg;

	@Test
	void testProperties(){
    
    
		System.out.println(msg);
	}
}
  • Advantages: It has a smaller impact range than the test environment in multi-environment development, and is only valid for the current test class

When starting the test environment, you can set the specific incoming parameters for the test environment through the args parameter

@SpringBootTest(args = {
    
    "--test.prop=testValue2"})
public class PropertiesAndArgsTest {
    
    
	@Value("${test.arg}")
	private String msg;

	@Test
	void testProperties(){
    
    
		System.out.println(msg);
	}
}

Load test-specific configuration

Use the @Import annotation to load the configuration specific to the current test class

@Configuration
public class MsgConig {
    
    
	
	@Bean
	public String msg() {
    
    
		return "bean msg";
	}
}
@SpringBootTest
@Import(MsgConfig.class)
public class ConfigurationTest {
    
    
	@Autowired
	private String msg;
	@Test
	void testConfiguration(){
    
    
		System.out.println(msg);
	}
}

Summarize:

Load test scope configuration is applied to a small scope test environment

Web environment simulation test

analog port

@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
public class WebTest {
    
    
	@Test
	void testRandomPort () {
    
    
	}
}

Virtual Request Test

@RestController
@RequestMapping("/books")
public class BookController {
    
    
	
	@GetMapping
	public String getById(){
    
    
		System.out.println("getById is running......");
		return "springboot";
	}
}
@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    
    
	@Test
	//注入虚拟MVC调用对象
	void testRandomPort (@Autowired MockMvc mvc) throws Exception {
    
    
			//创建虚拟请求,当前访问/books
			MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
			//执行请求
			mvc.perform(builder);
	}
}

Virtual Request Status Match

@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    
    
	@Test
	//注入虚拟MVC调用对象
	void testRandomPort (@Autowired MockMvc mvc) throws Exception {
    
    
			//创建虚拟请求,当前访问/books
			MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
			//执行请求
			ResultActions action = mvc.perform(builder);
			//匹配执行状态(是否预期值)
			//定义执行状态匹配器
			StatusResultMatchers status = MockMvcResultMatchers.status();
			//定义预期执行状态
			ResultMatcher ok = status.isOk();
			//使用本次真实执行结果与预期结果进行对比
			action.andExpect(ok);
	}
}

match response body

@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    
    
	@Test
	//注入虚拟MVC调用对象
	void testRandomPort (@Autowired MockMvc mvc) throws Exception {
    
    
			//创建虚拟请求,当前访问/books
			MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
			//执行请求
			ResultActions action = mvc.perform(builder);
			//匹配执行结果(是否预期值)
			//定义执行结果匹配器
			ContentResultMatchers content = MockMvcResultMatchers.content();
			//定义预期执行结果
			ResultMatcher result = content.string("springboot");
			//使用本次真实执行结果与预期结果进行对比
			action.andExpect(ok);
	}
}

Match response body (json)

Virtual request body (json) matching

@Data
public class Book {
    
    
	private int id;
	private String name;
	private String type;
	private String description;
}
@RestController
@RequestMapping("/books")
public class BookController {
    
    
	
	@GetMapping
	public String getById(){
    
    
		System.out.println("getById is running......");
		Book book = new Book();
		book.setId(1);
		book.setName("springboot");
		book.setType("springboot");
		book.setDescription("springboot");
	    return book;
	}
}
@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    
    
	@Test
	//注入虚拟MVC调用对象
	void testRandomPort (@Autowired MockMvc mvc) throws Exception {
    
    
			//创建虚拟请求,当前访问/books
			MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
			//执行请求
			ResultActions action = mvc.perform(builder);
			//匹配执行结果(是否预期值)
			//定义执行结果匹配器
			ContentResultMatchers content = MockMvcResultMatchers.content();
			//定义预期执行结果
			ResultMatcher result = content.json("{\"id\":1,\"name\":\"SpringBoot2\"}");
			//使用本次真实执行结果与预期结果进行对比
			action.andExpect(ok);
	}
}

match response header

dummy request header match

@SpringBootTest(webEnviroment = SpringBootTest.WebEnviroment.RANDOM_PORT)
//开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
    
    
	@Test
	//注入虚拟MVC调用对象
	void testRandomPort (@Autowired MockMvc mvc) throws Exception {
    
    
			//创建虚拟请求,当前访问/books
			MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books");
			//执行请求
			ResultActions action = mvc.perform(builder);
			//匹配执行结果(是否预期值)
			//定义执行结果匹配器
			HeaderResultMatchers content = MockMvcResultMatchers.header();
			//定义预期执行结果
			ResultMatcher result = content.string("Content-Type","application/json");
			//使用本次真实执行结果与预期结果进行对比
			action.andExpect(ok);
	}
}

Summarize:

web environment simulation test

  • set test port
  • Mock test starts
  • Simulation test matching (the information of each component can be matched)

Data layer test rollback

Data layer test transaction rollback

Add a transaction to the test case, and SpringBoot will roll back the transaction operation corresponding to the test case

@SpringBootTest
@Transactional
public class DaoTest {
    
    
	@Autowired
	private BookService bookService;
}

If you want to commit the transaction in the test case, you can set it through the @Rollback annotation

@SpringBootTest
@Transactional
@Rollback(false)
public class DaoTest {
    
    
}

Summarize:

Test case rollback transaction

Test case data setting

Test case data is usually tested with random values, and the random numbers provided by SpringBoot are used to assign them

testcase:
  book:
    id: ${
    
    random.int}        #随机数
    id2: ${
    
    random.int(10)}   #10以内随机数
    type: ${
    
    random.int(10,20)}   #10到20随机数
    uuid: ${
    
    random.uuid}      #随机uuid
    name: ${
    
    random.value}     #随机字符串,MD5字符串,32位
    publishTime: ${
    
    random.long} #随机整数(Long范围)
  • Where () can be any character, such as [] , !!

built-in data source

Data Layer Solutions

Existing data layer solution technology selection

Druid + MyBatis-Plus + MySQL
  • Data source: DruidDataSource
  • Persistence technology: MyBatis-Plus / MyBatis
  • Database: MySQL

Data source configuration format

Format one:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource

Format two:

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
      username: root
      password: root

Data source configuration

SpringBoot provides 3 embedded data source objects for developers to choose

  • HikariCP: default built-in data source object
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    hikari:
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root

Note: this url is at the same level as hikari

  • Tomcat provides DataSource: when HikariCP is not available, and in the web environment, the data source object configured by the tomcat server will be used
  • Commons DBCP: HikariCP is not available, the tomcat data source is not available, the dbcp data source will be used

JdbcTemplate

Data Layer Solutions

Built-in persistence solution - JdbcTemplate

@SpringBootTest
class SpringbootSSqlApplicationTest {
    
    
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Test
	void testJdbc(){
    
    
		String sql = "select * from tbl_book where id = 1";
		List<Book> query = jdbcTemplate.query(sql, new RowMapper<Book>() {
    
    
		@Override
		public Book mapRow(ResultSet rs,int rowNum) throws SQLException {
    
    
			Book temp = new Book();
			temp.setId(rs.getInt("id");
			temp.setName(rs.getString("name");
			temp.setType(rs.getString("type");
			temp.setDescription(rs.getString("description"));
			return temp;
		}
	});
	System.out.println(query);
  }
}

Use JdbcTemplate to introduce dependencies:

<dependency>
	<groupId>org.springframework.book</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

JdbcTemplate configuration:

spring:
  jdbc:
    template:
      query-timeout: -1   # 查询超时时间
      max-rows: 500       # 最大行数
      fetch-size: -1      # 批处理数量
      

Summarize:

1. SpringBoot built-in JdbcTemplate persistence solution
2. Use JdbcTemplate needs to import spring-boot-starter-jdbc


H2 database

Embedded database

SpringBoot provides 3 kinds of embedded databases for developers to choose to improve the efficiency of development and testing

  • H2
  • HSQL
  • Derby

Set the current project as a web project, and configure the H2 management console parameters

server:
  port: 80
spring: 
  datasource:
    url: jdbc:h2:~/test
    hikari:
      driver-class-name: org.h2.Driver
      username: sa
      password: 123456
  h2:
    console:
      path: /2
      enabled: true

Access user name sa, default password 123456

Browser, open the address localhost/h2 to view the h2 database in the browser

Operate the database (create tables)

create table tbl_book(id int,name varchar,type varchar,description varchar)

The H2 database console is only used in the development stage, please be sure to turn off the console function for online projects

server:
  port: 80
spring:
  h2:
    console:
      path: /h2
      enabled: false

Summarize:

  1. H2 embedded database startup method
  2. Please be sure to close the H2 database when running online

Data Layer Solutions

Existing data layer solution technology selection

Druid + MyBatis-Plus + MySQL
data source Persistence database
Druid MyBatis-Plus MySQL
HiKari MyBatis H2
JdbcTemplate

Database Layer Solution

SQL
NoSQL

NoSQL solutions

Common NoSQL solutions on the market

  • Redis
  • Mongo
  • ES

redis download installation and basic use

Redis is a memory-level NoSQL database with a key-value storage structure

  • Support multiple data storage formats
  • Support persistence
  • support cluster

Redis download (Windows version)

  • http://github.com/tporadowski/redis/releases

Redis installation and startup (Windows version)

  • Windows decompression installation or one-click installation
  • server start command
redis-server.exe redis.windows.conf
  • Client start command
redis-cli.exe

Summarize:

1.Redis installation (Windows version)
2.Redis basic operation


SpringBoot integrates Redis

1. Import SpringBoot to integrate Redis coordinates

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

2. Configure Redis coordinates (default configuration)

spring:
  redis:
    host: localhost # 127.0.0.1
    port: 6379
  • Host: localhost (default)
  • Port: 6379(default)

3. RedisTemplate provides an interface API for manipulating various data storage types

4. Client: RedisTemplate

@SpringBootTest
class SpringbootNosqlApplicationTests {
    
    
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		ops.set("testKey","testValue");
	}
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		Object val = ops.get("testKey");
		System.out.println(val);
	}
}
@SpringBootTest
class SpringbootNosqlApplicationTests {
    
    
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		HashOperations ops = redisTemplate.opsForHash();
		opsH.set("testKeyH","testFieldH","testValueH");
	}
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		HashOperations opsH = redisTemplate.opsForHash();
		Object valH = opsH.get("testKeyH","testFieldH");
		System.out.println(valH);
	}
}

Summarize:

SpringBoot integrates Redis

  • Import the starter corresponding to redis
  • configuration
  • Provide operation Redis interface object RedisTemplate
    - - ops : Get various data type operation interfaces

SpringBoot reads and writes Redis client

Client: RedisTemplate uses objects as key and value to serialize data internally

@SpringBootTest
class SpringbootNosqlApplicationTests {
    
    
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		ops.set("testKey","testValue");
	}
	@Test
	void set(@Autowired RedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		Object val = ops.get("testKey");
		System.out.println(val);
	}
}

Client: StringRediTemplate uses strings as key and value, which is equivalent to Redis client operation

@SpringBootTest
class SpringbootNosqlApplicationTests {
    
    
	@Test
	void set(@Autowired StringRedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		ops.set("testKey","testValue");
	}
	@Test
	void set(@Autowired StringRedisTemplate redisTemplate) {
    
    
		ValueOperations ops = redisTemplate.opsForValue();
		Object val = ops.get("testKey");
		System.out.println(val);
	}
}

Summary:
1.RedisTemplate
2.StringRedisTemplate (commonly used)


SpringBoot operates the Redis client to implement technology switching (jedis)

Client selection: jedis

<dependency>
 	<groupId>redis.clients</groupId>
 	<artifactId>jedis</artifactId>
</dependency>

configure client

spring:
	redis:
	  host: localhost # 127.0.0.1
	  port: 6379
	  clent-type: lettuce

Use jedis, clent-type to specify jedis, use lettuce, client type to specify lettuce (you can also not specify, the default is lettuce)

Configure client-specific properties

spring:
	redis:
	  host: localhost # 127.0.0.1
	  port: 6379
	  clent-type: lettuce
	  lettuce:
	    pool:
	      max-active: 16
	  jedis:
	    pool:
	      max-active: 16

The difference between lettcus and jedis

  • Jedis connects to the Redis server in a direct connection mode. When using jedis in the multi-line city mode, there will be security problems in the line city. The solution can be to configure the connection pool to make each connection dedicated, so that the overall performance will be greatly affected.
  • Letcus connects to the Redis server based on the Netty framework, and StatefulRedisConnection is used in the underlying design. StatefulRedisConnection itself is thread-safe and can guarantee concurrent access security issues, so a connection can be reused by multiple threads. Of course, lettcus also supports multiple connection instances to work together.

Summarize:

SpringBoot integrates Redis client selection

  • lettuce (default)
  • jedi

Introduction to Mongodb

MongoDB is an open source, high-performance, schema-free document database. One of the NoSQL database products, a non-relational database that is most like a relational database

Application scenario:

Taobao user data

  • Storage Location: Database
  • Features: Permanent storage, extremely low modification amount

Game equipment data, game props data

  • Storage Location: Database, Mongodb
  • Features: Combination of permanent storage and temporary storage, high bold style of modification quota

Live broadcast data, reward data, fan data

  • Storage Location: Database, Mongodb
  • Features: Combination of permanent storage and temporary storage, extremely high modification amount

IoT data

  • Storage location: Mongodb
  • Features: Temporary storage, rapid quota modification

Summarize:

Mongodb application scenarios


Mongodb download and installation

Download Mongo for Windows

  • https://www.mongodb.com/try/download

Windows version Mongo installation

  • Set the data directory after decompression

Mongo for Windows starts

- Server start

mongod --dbpath=//\data\db

- Client start

mongo -- host=12.0.0.1 --port=2701

Windows version Mongo installation problems and solutions

由于找不到VCRUNTIMEE140_1.dll,无法继续执行代码。重新安装程序可能会解决此问题。

Step 1: Download the corresponding dll file (you can search it through the Internet)

Step 2: Copy to the system32 directory under the windows installation path
Step 3: Execute the command to register the corresponding dll file

regsve32 vcruntime140_1.dll

Summarize:

  1. Mongodb installation and start
  2. Visual client Robo 3T installation and connection

Mongodb basic operations

Add

db.集合名称.insert/sava/insertOne(文档)

Revise

db.集合名称.remove(条件)

delete

db.集合名称.update(条件,{
    
    操作种类:{
    
    文件}})

1. Basic query

  • Query all: db.collection.find();
  • Check the first item: db.Collection.findOne()
  • Query a specified number of documents: db.collection.find().limit(10) //Check 10 documents
  • Skip the specified number of documents: db.collection.find().skip(20) //skip 20 documents
  • Statistics: db.Collection.count()
  • Sorting: db.Collection.sort({age:1}) //Sort in ascending order of age
  • Projection: db.collection name.find(condition,{name:1,age
  • :1}) //Only keep the name and age fields

2. Condition query

  • Basic format: db.collection.fing({condition})
  • Fuzzy query: db.collection.find({domain name:/regular expression/}) //equivalent to like in SQL, more powerful than like, and can execute all regular rules
  • Conditional comparison operation: db.collection.find({domain name:{$gt:value}}) //It is equivalent to the data comparison operation in SQL, for example: name>18
  • Include query: db.collection.find({domain name:{$in:[value 1, value 2]}}) //equivalent to in in SQL
  • Conditional connection query: db.collection.find({$and:[{condition 1},{tcondition 2}]}) //Equivalent to and and or in SQL

Summarize:

Mongodb basic CRUD


SpringBoot integrates Mongodb

Import Mongodb driver

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

configure client

spring:
  data:
    mondodb:
      url: mongodb://localhost/luxifa

Client reads and writes Mongodb

@Test
void testSave(@Autowired MongoTemplate mongoTemplate) {
    
    
	Book boo = new Book();
	book.setId(1);
	book.setType("springboot");
	book.setName("springboot");
	book.setDescription("springboot");
	mongoTemplate.save(book);
}

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

Summarize:

SpringBoot integrates Mongodb

  • Import the starer corresponding to Mongodb'
  • Configure mongodb access url
  • Provide operation Mongodb interface object MongoTemplate

## Cache- SpringBoot provides a unified integration interface for caching, which facilitates the development and management of caching technology
  • Generic
  • JCache
  • Ehcache
  • Hazelcat
  • Infinispan
  • Couchbase
  • Redis
  • Caffenine
  • Simple (default)
  • memcached

How to use Spring cache

- Import the starter corresponding to the caching technology

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

- enable caching

@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(SpringbootCacheApplication.class,args);
	}
}

- Set the result data of the current operation into the cache

@Cacheable(value="cacheSpace",key="#id")
public Book getById(Integer id) {
    
    
	return bookDao.selectById(id);
}

Summary:
The way SpringBoot starts the cache

- @EnableCaching
- Cacheable


Change cache provider Ehcache

  • ** Add Ehcache coordinates (cache provider implementation)**
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
</dependency>
  • The cache is set to use Ehcache
spring:
  cache:
    type: ehcahe
    ehcache:
      config: ehcache.xml
  • Provide echcache configuration file ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://echcache.org/ehcache.xsd"
         updateCheck="false">
	<!--默认缓存策略-->
	<!-- external: 是否永久存在,设置为true则不会被消除,此时与timeout冲突,通常设置为false-->
	<!-- diskPersistent: 是否启用磁盘持久化-->
	<!-- maxElementdInMemory: 最大缓存数量-->
	<!-- overflowToDisk: 超过最大缓存数据是否持久化到磁盘-->
	<!-- timeToldleSeconds: 最大不活动间隔,设置过长缓存容易溢出,设置过短无效果-->
	<!-- timeToLiveSeconds: 最大活时间-->
	<!-- memeryStoreEvictionPolicy: 缓存清除策略-->
	<defaultCache
			eternal="false"
			diskPersistent="false"
			maxElementsInMemory="1000"
			overflowToDisk="60"
			timeToldleSeconds="60"
			timeToLiveSeconds="60"
			memoryStoreEvictionPolict="LRU" />
</ehcache>
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://echcache.org/ehcache.xsd"
         updateCheck="false">
	<cache
	        name="smsCode"
			eternal="false"
			diskPersistent="false"
			maxElementsInMemory="1000"
			overflowToDisk="60"
			timeToldleSeconds="60"
			timeToLiveSeconds="60"
			memoryStoreEvictionPolict="LRU" />
</ehcache>

Summary:
Change the cache provider to Ehcache


Data Retirement Strategy

Related configurations affecting data elimination

Detect volatile data (dataset server.db[i].expires that may expire)

  • volatile-lru: Pick the least recently used data for elimination
  • volatile-lfu: select the least recently used data to eliminate
  • volatile-ttl: select data that will expire
  • volatile-random: random selection data elimination

Change cache provider Redis

  • Add Redis coordinates (cache provider implementation)
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>  
  • Configure the Redis server, the cache is set to use Redis
spring:
  redis:
    host: localhost
	port: 6379
  cache:
	type: redis
  • Set Redis related configuration
spring:
  redis:
    host: localhost
    port: 6379
  cache:
    type: redis
    redis:
      use-key-prefix: true  #是否使用前缀名(系统定义前缀名)
      key-prefix: sms_      #追加自定义前缀名
      time-to-live: 10s     #有效时长
      cache-null-value: false  #是否允许存储空值

Summarize:

Change provider to Redis


memcached download and installation

Install memcached

  • Run cmd command as administrator

Install

memcached.exe -d install

run memcached

  • start service
mamcached.exe -d start
  • Out of service
memcached.exe -d stop

Change cache provider memcached

  • Add Xmemcache coordinates (cache provider implementation)
<dependency>
	<groupId>com.googlecode.xmemcached</groupId>
	<artifactId>xmemcached</artifactId>
	<version>2.4.7</version>
</dependency>
  • Configure the necessary attributes of the memcached server
memcached:
	# memcached服务器地址
	servers: localhost:11211
	# 连接池的数量
	poolSize: 10
	# 设置默认操作超时
	opTimeout: 3000
  • Create a class to read attribute configuration information and load configuration
@Component
@ConfigurationProperties(prefix = "memcached")
@Data
public class XMemcachedProperties {
    
    
	private String servers;
	private Integer poolSize;
	private Long opTimeout;
}
  • Create a client configuration class
@Configuration
public class XMemcachedConfig {
    
    
	@Autowired
	private XMemcachedProperties xMemcachedProperties;
	@Bean
	public MemcachedClient getMemcachedClient() throws IOException{
    
    
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(xMemcachedProperties.getServers());
		MemcachedClient memcachedClient = builder.build();
		return memcachedClient;
	}
}
  • Configure memcached properties
@Service
public class SMSCodeServiceMemcacheImpl implements SMSCodeService {
    
    
	@Autowired
	private CodeUtils codeUtils;
	@Autowired
	private MemcachedClient memcachedClient;
	@Ovrride
	public String sendCodeToSMS(String tele) {
    
    
		String code = this.codeUtils.generator(tele);
		//将数据加入memcache
		try {
    
    
			memcachedClient.set(tele,0,code); //key,timeout,value
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return code;
	}




	public String checkCode(CodeMsg codeMsg) {
    
    
		String value = null;
		try {
    
    
			value = memcachedClient.get((code.getTele()).toString(); //key,timeout,value
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		return codeMsg.getCode().equals(value);
	}
}

Summary:
1.xmemcache client loading method (bean initialization)
2.xmemcache client usage method (set & get)


Change cache provider jetcache

  • jetCache encapsulates SpringCache, and realizes multi-level cache, cache statistics, automatic refresh, asynchronous call, data report and other functions based on the original functions

  • jetCache sets up a multi-level caching solution for local caching and remote caching
    Local caching (local) : linkedHashMap , Caffeine

    Remote cache (remote) : Redis , Tair

  • Add jetcache coordinates

<dependency>
	<groupId>com.alicp.jetcache</groupId>
	<artifactId>jetcache-starter-redis</artifactId>
	<version>2.6.2</version>
</dependency>
  • Configure the necessary properties of the remote cache
jetcache:
  remote:
    default:
      type: redis
      host: localhost
      port: 6379
      poolConfig:
        maxTotal: 50
    sms:
      type: redis
      host: localhost
      port: 6379
      poolConfig:
        maxTotal: 50
  • Configure the necessary properties of the local cache
jetcache:
  local:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
  • Configuration example
jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
      limit: 100
  remote:
    default:
      host: localhost
      port: 6379
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
  • Configuration property description
Attributes Defaults illustrate
jetcache.statIntervalMinutes 0 Statistics interval, 0 means no statistics
jetcache.hiddenPackages none When automatically generating name, hide the specified package name prefix
jetcache.(local或remote).${area}.type none Cache type, local support linkedhashmap, caffeine, remote support redis, tair
jetcache.(local或remote).${area}.keyConvertor none key converter, currently only supports fastjson
jetcache.(local或remote).${area}.valueEncoder java Only the remote type cache needs to be specified, java and kryo are optional
jetcache.(local或remote).${area}.valueDecoder java Only the remote type cache needs to be specified, java and kryo are optional
jetcache.(local或remote).${area}.limit 100 Only the cache of the local type needs to be specified, and the maximum number of elements of the cache instance
jetcache.(local或remote).${area}.expireAfterWriteInMillis Unprecedented Default expiration time, in milliseconds
jetcache.${area}.expireAfterAccessInmillis 0 Only local type caches are valid, in milliseconds, the maximum inactivity interval
  • Enable jetcacahe annotation support
@SpringBootApplication
@EnableCreateCacheAnnotation
public class SpringbootCacheApplication {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(SpringbootCacheApplication.class,args);
	}
}
  • Declare the cache object
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
    
    
	@Autowired
	private CodeUtils codeUtils;
	@CreateCache(name = "smsCache" , expire = 3600)
	private Cache<String,String> jetSMSCache;
}
  • cache operation
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
    
    
	@Override
	public String sendCodeToSMS(String tele) {
    
    
		String code = this.codeUtils.generator(tele);
		jetSMSCache.put(telw,code);
		return code;
	}

	@Override
	public boolean checkCode(CodeMsg codeMsg) {
    
    
		String value = jetSMSCache.get(codeMsg.getTele());
		return codeMsg.getCode().equals(value);
	}
}

Summarize:

1. Introduction to jetcache
2. How to use jetcache remote cache
3. How to use jetcache local cache


jetcache method caching

  • Enable method annotations
@SpringBootApplication
@EnableCreateCacheAnnotation
@EnableMethodCache(basePackages = "com.ithema")
public class SpringBootJetCacheApplication {
    
    
	public static void main(String[] args) {
    
    
		SpringApplication.run(SpringBootJetCacheApplication.class,args);
	}
}
  • Manipulating the cache using method annotations
@Service
public class BookServiceImpl implements BookService {
    
    
	@Autowired
	private BookDao bookDao;

	@Cache(name = "smsCache_",key = "#id", expire = 3600)
	@CacheRefresh(refresh = 10,timeUnit = TimeUnit.SECONDS)
	public Book getById(Integer id) {
    
    
		return bookDao.selectById(id);
	}
}
@Service
public class BookServiceImpl implement BookService {
    
    

	@CacheUpdate(name = "smsCache_", key = "#book.id", value = "#book")
	public boolean update(Book book) {
    
    
		return bookDao.updateById(book) > 0;
	}	

	@CacheInvalidate(name = "smsCache_", key = "#id")
	public boolean delete(Integer id) {
    
    
		return bookDao.deleteById(id) > 0;
	}
}
  • Cache objects must be guaranteed to be serializable
@Data
public class Book implements Serializable {
    
    
}
jetcache:
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java 

Summarize:

How to use jetcache method annotation


Basic operation of j2cache

  • j2cache is a cache integration framework, which can provide a cache integration method, so that various caches can be used together, and it does not provide caching functions.
  • Integration based on ehcache + redis

j2cache related configuration

  • Add j2cache coordinates, add coordinates of integrated cache
<dependency>
	<groupId>net.oschina.j2cache</groupId>
	<artifactId>j2cache-spring-boot2-starter</artifactId>
	<version>2.8.0-release</version>
</dependency>
<dependency>
	<groupId>net.oschina.j2cache</groupId>
	<artifactId>j2cache-core</artifactId>
	<version>2.8.4-release</version>
</dependency>
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>jehcache</artifactId>
</dependency>
  • Configure the use of j2cache (application.yml)
j2cache:
	config-location: j2cache.properties
  • Configure the first-level cache and the second-level cache and the sending method of the first-level cache data to the second-level cache (j2cache.properties)
# 配置1级缓存
j2cache.L1.provider_class = ehcache
ehcache.configXml = ehcache.xml

# 配置1级缓存数据到2级缓存的广播方式:可以使用redis提供的消息订阅模式,也可以使用groupd多播实现
j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy

# 配置2级缓存
j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProvider
j2cache.L2.config_section = redis
redis.hosts = localhost:6379

  • Set usage cache
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
    
    
	@Autowired
	private CodeUtils codeUtils;
	@Autowired
	private CacheChannel cacheChannel;
}
  • Set usage cache
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
    
    
	@Override
	public String sendCodeToSMS(String tele) {
    
    
		String code = codeUtils.generator(tele);
		cacheChannel.set("sms",tele,code);
		return code;
	}

	@Override
	public boolean checkCode(SMSCode smsCode) {
    
    
		String code = cacheChannel.get("sms",smsCode.getTele()).asString();
		return smsCode.getCode().equals(code);
	}
}

Summarize:

Basic use of j2cache caching

summary:

1.spring-cache
simple
ehcache
redis
memcached
2.jetcache
3.j2cache

Guess you like

Origin blog.csdn.net/weixin_42594143/article/details/129164048