In-depth analysis of how springboot configures multiple redis connections
Spring Boot provides automatic configuration for Redis, MongoDB, Elasticsearch, Solr and Gemfire. This article introduces in detail the configuration of multiple redis connections in springboot. Those who are interested can learn more.
1. springboot nosql Introduction
Spring Data provides other projects to help you use various NoSQL technologies including MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire, Couchbase and Cassandra. Spring Boot provides automatic configuration for Redis, MongoDB, Elasticsearch, Solr and Gemfire. You can take full advantage of other projects, but you need to configure them yourself.
1.1. Redis
Redis is a cache, message middleware and key-value storage system with rich features . Spring Boot provides automatic configuration for the Jedis client library and the Jedis client-based abstractions provided by Spring Data Redis. spring-boot-starter-redis 'Starter POM' provides a convenient way to collect dependencies.
Redis adds maven dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <!-- <version>1.3.5.RELEASE</version> --> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <!-- <version>1.3.6.RELEASE</version> --> </dependency>
1.2 Connecting to Redis
You can inject an automatically configured RedisConnectionFactory, StringRedisTemplate or an ordinary RedisTemplate instance that is the same as other Spring Beans . By default, this instance will try to connect to the Redis server using localhost:6379.
@Component public class MyBean { private StringRedisTemplate template; @Autowired public MyBean(StringRedisTemplate template) { this.template = template; } // ... }
If you add a @Bean of your own of any auto-configuration type, it will replace the default one (except in the case of RedisTemplate, which is excluded based on the bean's name 'redisTemplate' rather than its type ). If commons-pool2 exists in the classpath, you will get a connection pool factory by default.
1.3 Establish multiple redis connections
Use the default configuration of redis to connect to library 0 in redis. If you specify a library connection, you need to configure indexdb. At the same time, if you need to connect to multiple redis services, you also need to configure multiple data sources at the same time
1.3.1. Add:
@Component public class MyBean { private StringRedisTemplate template; @Autowired public MyBean(StringRedisTemplate template) { this.template = template; } // ... }
1.3.2. Create redisconfiguration
@Configuration public class Redis137_11Configuration { @Bean(name = "redis123Template") public StringRedisTemplate redisTemplate( @Value("${redis123.hostName}") String hostName, @Value("${redis123.port}") int port, @Value("${redis123.password}") String password, @Value("${redis123.maxIdle}") int maxIdle, @Value("${redis123.maxTotal}") int maxTotal, @Value("${redis123.index}") int index, @Value("${redis123.maxWaitMillis}") long maxWaitMillis, @Value("${redis123.testOnBorrow}") boolean testOnBorrow) { StringRedisTemplate temple = new StringRedisTemplate(); temple.setConnectionFactory(connectionFactory(hostName, port, password, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow)); return temple; } public RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle, int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) { JedisConnectionFactory jedis = new JedisConnectionFactory(); jedis.setHostName(hostName); jedis.setPort(port); if (!StringUtils.isEmpty(password)) { jedis.setPassword(password); } if (index != 0) { jedis.setDatabase(index); } jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow)); // 初始化连接pool jedis.afterPropertiesSet(); RedisConnectionFactory factory = jedis; return factory; } public JedisPoolConfig poolCofig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) { JedisPoolConfig poolCofig = new JedisPoolConfig(); poolCofig.setMaxIdle(maxIdle); poolCofig.setMaxTotal(maxTotal); poolCofig.setMaxWaitMillis(maxWaitMillis); poolCofig.setTestOnBorrow(testOnBorrow); return poolCofig; } }
1.3.3. Declare the redis abstract base class and create the redis operation method
public abstract class AbRedisConfiguration { protected StringRedisTemplate temple; public void setData(String key, String value) { getTemple().opsForValue().set(key, value); } public String getData(String key) { return getTemple().opsForValue().get(key); } public StringRedisTemplate getTemple() { return temple; } }
1.3.4. Create different subclasses according to the data source @Component
public class Redis123 extends AbRedisConfiguration { @Resource(name = "redis123Template") private StringRedisTemplate temple; public StringRedisTemplate getTemple() { return temple; } }
ps: The getTemple method and StringRedisTemple attribute are declared in the class and subclass at the same time. The subclass passes the subclass's own StringRedisTemple attribute to the parent class by overriding the getTeimple method of the parent class, and the parent class passes it through the subclass. The StringRedisTemple uses different data links to operate the cache. At this point, the parent class has completed all operation methods, and when you need to create a database connection, you only need to create a subclass, declare its own StringRedisTemple, and pass it to the parent class.
The above is the detailed content of In-depth analysis of how springboot configures multiple redis connections. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
