Configure using redis in Spring boot -- Annotation form, springredis --

Source: Internet
Author: User
Tags delete cache

Configure using redis in Spring boot -- Annotation form, springredis --

Following the template encoding method in the previous article, we used redis
Encoding format configuration (1)
Encoding format (2)

After in-depth study, we found that the annotation form is more useful, saving you some tedious code and making your code look more elegant.
For details about how to install the redis server, refer to encoding format configuration (1)

1. pom. xml

Add jar package support and use the redis starter that comes with springboot

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>        
2. Redis configuration file

The cache manager is added to manage redis.
Spring 3.1 introduces the annotation-based cache Technology, which is not a specific cache implementation solution (such as EHCache, OSCache, Redis, and so on ), instead, it is an abstraction of Cache Usage. By adding a small number of annotation defined in the existing code, it can achieve the effect of the returned object of the cache method.
RedisConfig. java

Import java. io. serializable; import lombok. extern. slf4j. slf4j; import org. springframework. beans. factory. annotation. value; import org. springframework. cache. cacheManager; import org. springframework. cache. annotation. cachingassumersupport; 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. data. redis. cache. redisCacheManager; import org. springframework. data. redis. connection. jedis. jedisConnectionFactory; import org. springframework. data. redis. core. hashOperations; import org. springframework. data. redis. core. listOperations; import org. springframework. data. redis. core. redisTemplate; import org. springframework. Data. redis. core. setOperations; import org. springframework. data. redis. core. valueOperations; import org. springframework. data. redis. core. ZSetOperations; import org. springframework. data. redis. serializer. jdkSerializationRedisSerializer; import org. springframework. data. redis. serializer. stringRedisSerializer; import java. lang. reflect. method; @ Slf4j @ Configuration @ EnableCaching // This annotation is very important; // inherit from CachingConfigure RSupport: to customize the KEY generation policy. It can not be inherited. Public class RedisConfig extends cachingassumersupport {// because the production and development environments use different startup resource files, @ Profile is used, used to specify the startup resource file @ Configuration @ Profile (value = {"dev"}) // Delete static class LocalConfiguration {// from application. properties to obtain the following parameter @ Value ("$ {redis. host} ") private String host; @ Value (" $ {redis. port} ") private Integer port; @ Value (" $ {redis. password} ") private String password;/*** cache manager. * @ param redi STemplate * @ return */@ Bean public CacheManager cacheManager (RedisTemplate <?,?> Response) {CacheManager cacheManager = new response (redisTemplate); return cacheManager;} @ Bean public redisTemplate <Serializable, Serializable> RedisTemplate (incluredisconnectionfactory) {log.info ("response ("------------------------------------------"); log.info ("----------------- local redis --------------"); log.info ("available"); RedisTemplate <Serializable, Serializable> redisTemplate = new RedisTemplate <Serializable, Serializable> (); // key serialization method; (otherwise, garbled characters will occur;). However, if the method has a non-String type such as Long, the type conversion error will be reported; // when you do not have a custom key generation policy, we recommend that you do not write the following code. You do not need to configure or implement ObjectRedisSerializer // or JdkSerializationRedisSerializer serialization; redisTemplate. setKeySerializer (new StringRedisSerializer (); redisTemplate. setHashKeySerializer (new StringRedisSerializer (); redisTemplate. setValueSerializer (new JdkSerializationRedisSerializer (); redisTemplate. setHashValueSerializer (new JdkSerializationRedisSerializer (); // the above four configurations do not need redisTemplate. setConnectionFactory (redisConnectionFactory); return redisTemplate;} @ Bean public JedisConnectionFactory redisConnectionFactory () {JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory (); redisConnectionFactory. setHostName (host); redisConnectionFactory. setPort (port); redisConnectionFactory. setPassword (password); return redisConnectionFactory;}/*** custom key. * This method generates a unique key */@ Override public KeyGenerator keyGenerator () {log.info ("RedisCacheConfig. keyGenerator () "); return new KeyGenerator () {@ Override public Object generate (Object o, Method method, Object... objects) StringBuilder sb = new StringBuilder (); sb. append (o. getClass (). getName (); sb. append (method. getName (); for (Object obj: objects) {sb. append (obj. toString ();} log.info ("keyGenerator =" + sb. toString (); return sb. toString ();}};}}

@ Profile (value = {"dev"}) represents the configuration used in the Development Environment
@ Slf4j is the annotation in lombok. You can delete it if you do not need it.

3. Use Cases
Import java. io. serializable; import java. util. list; import javax. annotation. resource; import lombok. extern. slf4j. slf4j; import org. springframework. beans. factory. annotation. autowired; import org. springframework. data. redis. core. redisTemplate; import org. springframework. data. redis. core. valueOperations; import org. springframework. stereotype. service; import org. springframework. transaction. annotation. transaction Al; import com. github. pagehelper. pageHelper; @ Slf4j @ Transactional @ Servicepublic class UserServiceImpl implements IUserService {@ Autowired private IUserDao userDao; // because the configuration file inherits cachingassumersupport, if no key is specified, it is generated using the default KEY generation policy. Here we specify KEY @ Cacheable (value = "userInfo", key = "'finduser' + # id ", condition = "# id % 2 = 0 ") // specify the Cache name in the value Attribute // use the key attribute to customize the key // specify the condition that occurs in the condition attribute (as shown in the preceding example, the condition is entered only when the user id is an even number. Row cache) @ Override public UserDto findProperty (String id) {UserDto user = userDao. findUser (id); return user;}/***** @ CachePut can also declare a method to support caching. * Unlike @ Cacheable, the method marked with @ CachePut does not check whether the cache has previously executed results before execution. * instead, the method is executed every time, the execution results are stored in the specified cache as key-value pairs. ** // @ CachePut ("users") // The method is executed each time, and the result is saved to the specified cache @ Override public List <UserDto> mybatisQueryAll () {return userDao. selectAll () ;}@ Override // @ CacheEvict (value = "propertyInfo", allEntries = true) Clear all // Delete the specified cache @ CacheEvict (value = "propertyInfo ", key = "'finduser' + # id") // other attributes // allEntries is of the boolean type, indicating whether to clear all elements in the cache. The default value is false, indicating no need. When allEntries is set to true, Spring Cache ignores the specified key. // By default, the clear operation is triggered after the corresponding method is successfully executed. That is, if the method fails to return successfully because of an exception thrown, the clear operation is not triggered. // Using beforeInvocation can change the time when the cleanup operation is triggered. When we set this attribute value to true, Spring will clear the specified elements in the cache before calling this method. Public String cacheEvict (String id) {log.info ("delete cache" + id); return null ;} /*** @ Caching annotation allows us to specify multiple annotations related to Spring Cache in one method or class at the same time. * It has three attributes: cacheable, put, and evict, which are used to specify @ Cacheable, @ CachePut, and @ CacheEvict respectively. */@ Caching (cacheable = @ Cacheable ("users"), evict = {@ CacheEvict ("cache2"), @ CacheEvict (value = "cache3 ", allEntries = true)}) public UserDto find (Integer id) {return null ;}}

For more information, see annotations.
Does it feel that the annotation form code is very elegant?
If you have any questions, please leave a message ^

Top
2
Step on
0
View comments

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.