SoFunction
Updated on 2025-03-03

Springboot integrates AOP and redis examples

aop

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Turn on automatic proxy

Note: After completing the introduction of the AOP dependency package, generally there is no need to do other configurations. People who have used Spring annotation configuration method will ask whether they need to add @EnableAspectJAutoProxy to the main class of the program to enable it, which is not actually necessary.

Because in the default configuration properties of AOP, the properties are enabled by default, that is, as long as the AOP dependency is introduced, @EnableAspectJAutoProxy has been added by default.

Log section

@Component
@Aspect
@Slf4j
public class WebLogAspect {
    @Pointcut("(execution(public * ..*.*(..))) || (execution(public * ..*.*(..)))")
    public void pointcut(){
​
    }
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) ();
        if(attributes!=null){
            HttpServletRequest request = ();
            ("Request Address URL:"+().toString());
            ("Request method HTTP_METHOD:"+());
            ("Client Address IP:"+());
            ("Access method CLASS_METHOD:"+().getDeclaringTypeName());
            ("Argument parameter ARGS in the method:"+ (()));
        }
    }
}

Format:

  • execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
  • Modifier-pattern?
  • Return value matching (ret-type-pattern) can represent any return value for *, class name of the full path, etc.
  • Classpath matching (declaring-type-pattern?)
  • Method name matching (name-pattern) can specify the method name or represent all methods, set represents all methods starting with set
  • Parameter matching ((param-pattern)) can specify a specific parameter type, multiple parameters are separated by "," and each parameter can also use "" to represent parameters of any type, such as (String) to match a String parameter; (,String) to represent methods that match two parameters, the first parameter can be of any type, and the second parameter is of a String type; (..) can be used to represent zero or more arbitrary parameters.
  • Exception type matching (throws-pattern?)
  • The option is followed by "?"

druid database connection pool

refer to

Redis springboot integrates redis

&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;!--lettucerelycommons-pool2--&gt;
&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;commons-pool2&lt;/artifactId&gt;
    &lt;version&gt;2.8.0&lt;/version&gt;
&lt;/dependency&gt;

yaml

 spring:
     redis:
        host: 127.0.0.1
        port: 6379
        password:
        lettuce:
          pool:
            max-active: 8 #The maximum number of connections to the connection pool (using negative values ​​to indicate no limit) is 8 by default            max-wait: -1ms #Maximum blocking waiting time for connection pools (using negative values ​​to indicate no limit) defaults to -1            max-idle: 8 #Maximum idle connection in connection pool default is 8            min-idle: 5 # Minimum idle connection in connection pool Default is0

Automatic configuration, reference:

RedisConfig

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // Configure redisTemplate        RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;String, Object&gt;();
        (redisConnectionFactory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        (stringSerializer); // key serialization        (new GenericJackson2JsonRedisSerializer()); // value serialization        (stringSerializer); // Hash key serialization        (new GenericJackson2JsonRedisSerializer()); // Hash value serialization        ();
        return redisTemplate;
    }
​
}

RedisService

public interface RedisService {
    void setObj(String key, Object obj, long timeout);
    void setObj(String key, Object obj);
    Object getObj(String key);
}
@Service("redisService")
public class RedisServiceImpl implements RedisService {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void setObj(final String key, Object obj, long timeout) {
        ValueOperations<Serializable, Object> operations = ();
        (key, obj, timeout, );
    }
​
    @Override
    public void setObj(String key, Object obj) {
        setObj(key,obj,60*60*15);
    }
​
    @Override
    public Object getObj(final String key) {
        Object o = ().get(key);
        return o;
    }
​
}

use

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RedisService redisService;
       @Override
    public Customer selectByPrimaryKey(Integer id) {
        Customer customer = (Customer)("springboot:ssm:customer:"+id);
        if(customer==null){
            customer = (id);
            ("springboot:ssm:customer:"+id,customer);
        }
        return customer;
    }
}

Client Tools

In the later Springboot integrates redis, the connection pool will be used, so here we will introduce the connection pool in Redis:

Client connection Redis uses the TCP protocol. The direct connection method requires establishing a TCP connection every time, while the connection pool method can pre-initialize the client connection, so you only need to borrow from the connection pool each time. The borrowing and return operations are performed locally, with only a small amount of concurrent synchronization overhead, which is far less than the overhead of creating a new TCP connection. In addition, the direct connection method cannot limit the number of redis client objects, which may cause connection leakage in extreme cases, and the form of a connection pool can effectively protect and control the use of resources

Let’s take the Jedis client as an example, and then summarize the comparison between the client’s direct connection method and the connection pool method.

advantage shortcoming
Direct connection Simple and convenient, suitable for a small number of long-term connection scenarios 1. There is overhead for each new/closing TCP connection. 2. The resource cannot be controlled, and the connection leak occurs in extreme cases. 3. The Jedis object is thread-insecure (The Lettuce object is thread-safe)
Connection pool 1. No need to generate Jedis objects per connection, reducing overhead 2. Use the form of a connection pool to protect and control the use of resources Compared with direct connection, it is more troublesome to use, especially in resource management, many parameters are required to ensure that, and problems will arise once the planning is unreasonable.

Jedis vs Lettuce

Jedis and Lettuce are clients that operate Redis in Java. In Spring Boot version, Jedis is used by default, while in Spring Boot version, Lettuce is used by default. The difference between Jedis and Lettuce is as follows:

Jedis is a direct connection redis server in implementation. If it is non-threaded in a multi-threaded environment, only connection pools are used at this time to add physical connections to each Jedis instance. Lettuce's connection is based on Netty. The connection instance (StatefulRedisConnection) can be accessed concurrently between multiple threads. It should be that StatefulRedisConnection is thread-safe. Therefore, a connection instance (StatefulRedisConnection) can meet concurrent access in a multi-threaded environment. Of course, this is also a scalable design. If a connection instance is insufficient, you can also add connection instances as needed.

Lettuce

Same as 4.1

jedis

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId></groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
​
<dependency>
    <groupId></groupId>
    <artifactId>jedis</artifactId>
</dependency>

yml

spring:
     redis:
        host: 127.0.0.1
        port: 6379
        password:
        jedis:
          pool:
            max-active: 8 #The maximum number of connections to the connection pool (using negative values ​​to indicate no limit) is 8 by default            max-wait: -1ms #Maximum blocking waiting time for connection pools (using negative values ​​to indicate no limit) defaults to -1            max-idle: 8 #Maximum idle connection in connection pool default is 8            min-idle: 5 # Minimum idle connection in connection pool Default is0

This is the end of this article about Springboot integrating AOP and redis. For more related Springboot integrating AOP and redis, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!