1. Integrate Druid
1.1 Introduction to Druid
A large part of Java programs need to operate the database. In order to improve performance, when operating the database, you have to use the database connection pool.
Druid is a database connection pool implementation on Alibaba's open source platform. It combines the advantages of DB pools such as C3P0 and DBCP, and also adds log monitoring.
Druid is a database connection pool designed for monitoring, which can effectively monitor the connection status of the database connection pool and SQL execution status.
1.2 Add Druid data source dependency
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version> </dependency>
1.3 Use Druid data source
server: port: 8080 spring: datasource: druid: url: jdbc:mysql://localhost:3306/eshop?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true username: xxx password: xxx driver-class-name: com.mysql.cj.jdbc.Driver initial-size: 10 max-active: 20 min-idle: 10 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 stat-view-servlet: enabled: true login-username: admin login-password: 1234 logging: level: com.wyy.spring.Dao: debug
Test to see if it is successful!
package com.wyy.spring; import com.wyy.spring.Dao.StudentMapper; import com.wyy.spring.service.StudentService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; @SpringBootTest class SpringBoot04ApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() { System.out.println(dataSource.getClass()); } }
Print results
2. Integrate redis
2.1 Add redis dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.2 yml adds redis configuration information
redis: database: 0 host: 120.0.0.0 port: 6379 password: xxxx jedis: pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0 timeout: 10000
2.3 redis configuration class
package com.wyy.spring.conf; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.util.ClassUtils; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.time.Duration; @Configuration @EnableCaching public class RedisConfiguration extends CachingConfigurerSupport { @Bean @Primary /** * 缓存管理器 */ CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .computePrefixWith(cacheName -> cacheName + ":-cache-:") /*设置缓存过期时间*/ .entryTtl(Duration.ofHours(1)) /*禁用缓存空值,不缓存null校验*/ .disableCachingNullValues() /*设置CacheManager的值序列化方式为json序列化,可使用加入@Class属性*/ .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer( new GenericJackson2JsonRedisSerializer() )); /*使用RedisCacheConfiguration创建RedisCacheManager*/ RedisCacheManager manager = RedisCacheManager.builder(factory) .cacheDefaults(cacheConfiguration) .build(); return manager; } public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(factory); RedisSerializer stringSerializer = new StringRedisSerializer(); /* key序列化 */ redisTemplate.setKeySerializer(stringSerializer); /* value序列化 */ redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); /* Hash key序列化 */ redisTemplate.setHashKeySerializer(stringSerializer); /* Hash value序列化 */ redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; @Override public KeyGenerator keyGenerator() { return (Object target, Method method, Object... params) -> { final int NO_PARAM_KEY = 0; final int NULL_PARAM_KEY = 53; StringBuilder key = new StringBuilder(); /* Class.Method: */ key.append(target.getClass().getSimpleName()) .append(".") .append(method.getName()) .append(":"); if (params.length == 0) { return key.append(NO_PARAM_KEY).toString(); } int count = 0; for (Object param : params) { /* 参数之间用,进行分隔 */ if (0 != count) { key.append(','); } if (param == null) { key.append(NULL_PARAM_KEY); } else if (ClassUtils.isPrimitiveArray(param.getClass())) { int length = Array.getLength(param); for (int i = 0; i < length; i++) { key.append(Array.get(param, i)); key.append(','); } } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) { key.append(param); } else { /*JavaBean一定要重写hashCode和equals*/ key.append(param.hashCode()); count++; return key.toString(); }; }
@CacheConfig A class-level annotation that allows sharing of cached cacheNames, KeyGenerator, CacheManager and CacheResolver
@Cacheable Used to declare that a method is cacheable. Cache the results of an executed method so that subsequent calls with the same parameters do not need to execute the actual method again. Get the value directly from the cache
The method marked with @CachePut will not check whether there is a previously executed result in the cache before execution. Instead, the method will be executed every time and the execution result will be expressed as a key value. The correct form is stored in the specified cache.
The function of @CacheEvict is mainly for method configuration and can clear the cache according to certain conditions
The above is the detailed content of How SpringBoot integrates Druid and Redis. For more information, please follow other related articles on the PHP Chinese website!

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version
Useful JavaScript development tools
