Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How SpringBoot integrates Druid and Redis

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how SpringBoot integrates Druid and Redis. It is very detailed and has a certain reference value. Friends who are interested must finish it!

1. Introduction to Integrated Druid1.1Druid

A large part of Java programs operate the database, and database connection pooling has to be used when operating the database to improve performance.

Druid is a database connection pool implementation on Alibaba's open source platform, which combines the advantages of DB pools such as C3P0 and DBCP, and adds log monitoring.

Druid can well monitor the execution of DB pooled connections and SQL, and is born for monitoring DB connection pooling.

1.2 add Druid data source dependency com.alibaba druid-spring-boot-starter 1.2.8 1.3 use Druid data source server: port: 8080spring: 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: 1234logging: level: com.wyy.spring.Dao: debug

Test it to see if it works!

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;@SpringBootTestclass SpringBoot04ApplicationTests {@ Autowired DataSource dataSource; @ Test void contextLoads () {System.out.println (dataSource.getClass ());}}

Print the result

two。 Integrate redis2.1, add redis dependency org.springframework.boot spring-boot-starter-data-redis 2.2yml, add 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: 100002.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@EnableCachingpublic class RedisConfiguration extends CachingConfigurerSupport {@ Bean @ Primary / * Cache Manager * / CacheManager cacheManager (RedisConnectionFactory factory) {RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig () .computePrefixWith (cacheName-> cacheName + ":-cache-:") / * set cache expiration * / .entryTtl (Duration.ofHours (1)) ) / * disable cache null Do not cache null check * / .serialCachingNullValues () / * set the value serialization mode of CacheManager to json serialization. You can add the @ Class attribute * / .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (new GenericJackson2JsonRedisSerializer () / * use RedisCacheConfiguration to create RedisCacheManager*/ RedisCacheManager manager = RedisCacheManager.builder (factory) .cacheDefaults (cacheConfiguration) .build (); return manager;} public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate redisTemplate = new RedisTemplate (); redisTemplate.setConnectionFactory (factory); RedisSerializer stringSerializer = new StringRedisSerializer () / * key serialization * / redisTemplate.setKeySerializer (stringSerializer); / * value serialization * / redisTemplate.setValueSerializer (new GenericJackson2JsonRedisSerializer ()); / * Hash key serialization * / redisTemplate.setHashKeySerializer (stringSerializer); / * Hash value serialization * / 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) .append () } int count = 0; for (Object param: params) {/ * parameters are used to separate * / 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) ) {key.append (Array.get (param, I)); key.append (',');}} else if (ClassUtils.isPrimitiveOrWrapper (param.getClass ()) | | param instanceof String) {key.append (param) } else {/ * JavaBean must rewrite hashCode and 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 is used to declare that the method is cacheable. Store the results in the cache so that subsequent calls with the same parameters do not need to execute the actual square method. Take the value directly from the cache

The @ CachePut annotated method does not check whether there is a previously executed result in the cache before execution, but executes the method each time and stores the execution result in the specified cache in the form of a key-value pair.

The function of @ CacheEvict is mainly aimed at method configuration, and can clear the cache according to certain conditions.

The above is all the contents of the article "how SpringBoot integrates Druid and Redis". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report