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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic
