Cache is now almost all of the large and medium websites are using the kill skill, reasonable use of cache can not only improve the speed of website access, but also greatly reduce the pressure of the database. Redis provides key expiration, as well as flexible key obsolescence strategies, so Redis is now used in many caching situations.

Redis is installed on centos and Redis is installed on centos. Redis is installed on centos and Redis is installed on centos. Today’s main introduction introduces springboot integration Redis.

V Application Scenarios

At present, the company’s projects are focused on forum/community/social products, so the practical scenarios of Redis mainly focus on the leaderboard, the latest/hottest content, and the ordered collection data structure provided by Redis can realize a variety of complex leaderboard applications. There are also basic functions of social networking sites, such as liking, treading, following/being followed, and mutual friends. Generally, the traffic volume of social networking sites is relatively large, and the traditional relational database type is not suitable for storing this type of data. The data structure provided by Redis, such as hash and collection, can conveniently realize these functions.

There are also many application scenarios, such as distributed session and distributed lock (distributed lock interested can see my previous article “Java distributed lock, understand the implementation of distributed lock read this article), etc., in short, more and more widespread.

V builds Redis

1.1 introduction of Redis

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <! --<dependency>--> <! --<groupId>redis.clients</groupId>--> <! --<artifactId>jedis</artifactId>--> <! - < version > 2.9.0 < / version > -- > <! --</dependency>-->Copy the code

Note that redis. Clients is used locally for debugging tests and can be ignored.

1.2. Add RedisCacheConfig

package com.demo.Redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import java.util.concurrent.CountDownLatch; /** * Created by toutou on 2019/1/20. */ @Configuration @EnableCaching public class RedisCacheConfig { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();  container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } public class Receiver { private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { latch.countDown(); }}}Copy the code

You can add as needed or ignore as needed.

1.3. Add Redis configuration and modify application.properties

# ----- Redis -------- # # Redis (RedisProperties) # Redis database index (default 0) Spring.redis. Database =0 # Redis server address Port =6379 # Redis server connection password (default: empty) Spring.redis. password= # Spring.redis.pool. max-active=8 # Maximum connection pool waiting time (negative value indicates no limit) Spring.redis.pool. max-wait=-1 # Spring.redis.pool. max-idle=8 # Spring.redis.pool. min-idle=0 # Connection timeout (ms) spring.redis.timeout=5000Copy the code

1.4. Add the Service

package com.demo.service;

import com.demo.pojo.UserDetails;

/**
 * Created by toutou on 2018/10/15.
 */
public interface UserService {
    UserDetails getUserDetailsByUid(int uid);
    String getUserNameById(Integer uid);
    void setUserNameById(Integer uid, String userName);
}
Copy the code

UserServiceImpl

package com.demo.service; import com.demo.dao.UserDetailsMapper; import com.demo.dao.UserPositionMapper; import com.demo.pojo.UserDetails; import com.demo.pojo.UserPosition; import com.google.common.base.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.List; /** * Created by toutou on 2018/10/15. */ @Service public class UserServiceImpl implements UserService{ @Autowired UserDetailsMapper userDetailsMapper; @Autowired UserPositionMapper userPositionMapper; @Autowired StringRedisTemplate template; static final String KEY_USER_INFO__NAME = "com_demo_user_info_007_%s"; Public String getUserNameById(Integer uid){String userName = "unknown user "; try { userName = template.opsForValue().get(String.format(KEY_USER_INFO__NAME, uid)); If (strings. isNullOrEmpty(userName)) {// Redis does not read database UserDetails UserDetails = getUserDetailsByUid(uid); if (userDetails ! = null && ! Strings.isNullOrEmpty(userDetails.getCity())) { userName = userDetails.getCity(); } } }catch(Exception e){ System.out.println(e.toString()); } return userName; } public void setUserNameById(Integer uid, String userName){ template.opsForValue().set(String.format(KEY_USER_INFO__NAME, uid), userName); } public UserDetails getUserDetailsByUid(int uid){ return userDetailsMapper.getUserDetailsByUid(uid); }}Copy the code

1.5. Add RedisController

package com.demo.controller; import com.demo.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import redis.clients.jedis.Jedis; /** * Created by toutou on 2019/1/20. */ @RestController @Slf4j public class RedisController { @Autowired UserService userService; @RequestMapping(value = "/getusernamebyid") public String getUserNameById(Integer uid) { return userService.getUserNameById(uid); } @RequestMapping(value = "/setusernamebyid") public String setUserNameById(Integer uid, String uname) { userService.setUserNameById(uid, uname); Return "Set successfully "; } @requestMapping (value = "/jedistest") public String jedistest (){RequestMapping(value = "/jedistest") public String jedistest (){jedis jedis = new jedis (" IP ", 6379); Jedis.set ("key1", "test01"); String key1 = jedis.get("key1"); System.out.println(key1 + " " + key1); // Close jedis jedis.close(); return key1; }}Copy the code

Note that jedisTest is for my local debug tests and can be ignored.

VRedis tests the effect

V Source code address

Github.com/toutouge/ja…

About the author: Focus on basic platform project development. If you have any questions or suggestions, please feel free to comment! Copyright notice: The copyright of this article belongs to the author and the blog garden, welcome to reprint, but without the consent of the author must retain this statement, and give the original text link in a prominent place on the page of the article. For the record: all comments and messages will be answered as soon as possible. You are welcome to correct your mistakes and make progress together. Or direct private message I support the blogger: if you think the article is helpful to you, you can click on the lower right corner of the article [recommendation]. Your encouragement is the author to adhere to the original and continuous writing of the biggest power! \