Our task is introduced

This blog is our Task: a complete list management system tutorial document on Github. It is a front and back separated list management tool developed by SpringBoot+Vue, which imitatestick lists. At present, it has been deployed on Ali Cloud ECS, which can be previewed online and used at will (with detailed tutorial). If you are interested, welcome to give a star!

Aliyun preview address

Redis installation and configuration

Redis installation and configuration under Windows

SpringBoot integrate Redis

Adding project dependencies

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </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-data-redis</artifactId> </dependency> </dependencies>Copy the code

Yml file configuration

Yml file is mainly about Redis configuration, where the key setting format is: database name: table name: ID, more Redis understand, please refer to this article.

Redis various key typical use scenario, not clear all take a look

# DataSource Config Spring: redis: # redis host: localhost # redis database index (default: 0) 6379 # Redis server connection password (default empty) password: jedis: pool: # Maximum number of connections in the connection pool (negative value indicates no limit) max-active: Max-wait: -1ms # Maximum idle connection in the connection pool max-idle: 8 # Minimum idle connection in the connection pool min-idle: 0 # Connection timeout (ms) timeout: 3000ms # Custom redis key Redis: database: "study" key: user: "user" expire: common: 86400 # 24 hoursCopy the code

Entity class

Create an Entity package and create the User class under the package to be used as the operation entity of Demo. I’m going to go straight to Setter/Getter because some of you may not know Lombok yet.

package com.example.demo.entity; /** * @program: springboot-redis-demo * @description: user class * @author: water76016 * @create: 2020-12-29 09:22 **/ public class User { Integer id; String username; String password; public User(Integer id, String username, String password) { this.id = id; this.username = username; this.password = password; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}Copy the code

Service Service interface

There are two service interfaces: UserService and RedisService. UserService provides a service for User entities, and RedisService provides a service interface for operating Reids.

package com.example.demo.service; import com.example.demo.entity.User; Public interface UserService {/** * * @param user * @return */ public String helloUser(user user); }Copy the code
package com.example.demo.service; import java.util.List; import java.util.Map; import java.util.Set; /** * @program: our-task * @description: redis * @author: water76016 * @create: 2020-09-24 16:45 **/ public interface RedisService {/** ** save attributes ** @param key the key * @param value the value * @param  time the time */ void set(String key, Object value, long time); /** * save attributes ** @param key * @param value */ void set(String key, Object value); ** @param key the key * @return the object */ object get(String key); /** * delete attribute ** @param key the key * @return the Boolean */ Boolean del(String key); ** @param keys the keys * @return the long */ long del(List<String> keys); /** * set expire time ** @param key the key * @param time the time * @return the Boolean */ Boolean expire(String key, long time); /** * getExpire time ** @param key the key * @return the expire */ Long getExpire(String key); ** @param key the key * @return the Boolean */ Boolean hasKey(String key); /** * increment by delta ** @param key the key * @param delta the delta * @return the long */ long incr(String key, long delta); /** * @param key the key * @param delta the delta * @return the long */ long decr(String key, long delta); /** * return the object */ object hGet(String key, String key) String hashKey); /** * Puts an attribute into the Hash structure ** @param key the key * @param hashKey the Hash key * @param value the value * @param time the time * @return the boolean */ Boolean hSet(String key, String hashKey, Object value, long time); /** * Put an attribute into the Hash structure ** @param key the key * @param hashKey the Hash key * @param value the value */ void hSet(String) key, String hashKey, Object value); ** @param key the key * @return the map */ map <Object, Object> hGetAll(String key); /** * Directly set the Hash structure ** @param key the key * @param map the map * @param time the time * @return the Boolean */ Boolean hSetAll(String key, Map<String, Object> map, long time); ** @param key the key * @param map the map */ void hSetAll(String key, map <String, Object> map); ** @param key the key * @param hashKey the Hash key */ void hDel(String key, Object... hashKey); /** * Determine if the attribute exists in the Hash structure ** @param key the key * @param hashKey the Hash key * @return the Boolean */ Boolean hHasKey(String key, String hashKey); /** * increments the attribute in the Hash structure ** @param key the key * @param hashKey the Hash key * @param delta the delta * @return the long */ Long hIncr(String key, String hashKey, Long delta); /** * attribute declination in Hash structure ** @param key the key * @param hashKey the Hash key * @param delta the delta * @return the long */ Long hDecr(String key, String hashKey, Long delta); ** @param key the key * @return the Set */ Set<Object> sMembers(String key); /** * add attribute to Set ** @param key the key * @param values the values * @return the long */ long sAdd(String key, Object... values); /** * add attribute to Set structure ** @param key the key * @param time the time * @param values the values * @return the long */ long sAdd(String key, long time, Object... values); ** @param key the key * @param value the value * @return the Boolean */ Boolean sIsMember(String key, Object value); ** @param key the key * @return the long */ long sSize(String key); ** @param key the key * @param values the values * @return the long */ long sRemove(String key, Object... values); ** @param key the key * @param start the start * @param end the end * @return the List */ List<Object> lRange(String key, long start, long end); ** @param key the key * @return the long */ long lSize(String key); ** @param key the key * @param index the index * @return the object */ object lIndex(String key, long index); /** * add attribute to List ** @param key the key * @param value the value * @return the long */ long lPush(String key, Object value); /** * Add attribute to List ** @param key the key * @param value the value * @param time the time * @return the long */ long lPush(String key, Object value, long time); ** @param key the key * @param values the values * @return the long */ long lPushAll(String key, Object... values); ** @param key the key * @param time the time * @param values the values * @return the long */ long  lPushAll(String key, Long time, Object... values); /** * Remove attribute from List structure ** @param key the key * @param count the count * @param value the value * @return the long */ long lRemove(String key, long count, Object value); }Copy the code

The Service implementation class

In UserService, we store user information in Redis. The RedisService method is called and an expiration time is set for the key. You can use the methods in RedisService directly. These methods are quite comprehensive.

package com.example.demo.service.impl; import com.example.demo.entity.User; import com.example.demo.service.RedisService; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * @program: springboot-redis-demo * @description: user service implementation * @author: water76016 * @create: 2020-12-29 09:24 **/ @Service public class UserServiceImpl implements UserService { @Autowired RedisService redisService; @Value("${redis.database}") private String redisDatabase; @Value("${redis.key.user}") private String redisUserKey; @Value("${redis.expire.common}") private long expire; @override public String helloUser(user user) {Override public String helloUser(user user) { The key format is as follows: Database name: user: user ID String key = redisDatabase + ":" + redisUserKey + ":" + user.getid (); Redisservice.set (key, user.toString())); Redisservice.expire (key, expire); return user.toString(); }}Copy the code
package com.example.demo.service.impl;

import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @program: our-task
 * @description: redis操作服务接口实现类
 * @author: water76016
 * @create: 2020-09-24 16:45
 **/
@Service
public class RedisServiceImpl implements RedisService {
    /**
     * 由于没有指定具体类型<String, Object>,用Resource注入才有效
     * */
    @Resource
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }
    
    @Override
    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, Object value) {

        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public Long del(List<String> keys) {
        return redisTemplate.delete(keys);
    }

    @Override
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    @Override
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    @Override
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    @Override
    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    @Override
    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    @Override
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    @Override
    public void hSetAll(String key, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    @Override
    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    @Override
    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    @Override
    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    @Override
    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    @Override
    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    @Override
    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    @Override
    public Long sAdd(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    @Override
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    @Override
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    @Override
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    @Override
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    @Override
    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    @Override
    public Long lPush(String key, Object value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }

    @Override
    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    @Override
    public Long lPushAll(String key, Long time, Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }
}
Copy the code

UserController controller

Next, we create a new Controller package and create a new UserController control class under that package.

package com.example.demo.controller; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @program: SpringBoot-Redis-Demo * @description: * @author: water76016 * @create: 2020-12-29 09:27 **/ @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @PostMapping("/helloUser") public String helloUser(@RequestBody User user){ return userService.helloUser(user); }}Copy the code

Results of the test

Finally, we launch the SpringBoot program, which runs on port 8080, and tests it in Postman. If you follow my input in Postman, you’ll get the corresponding output.

Also, let’s see if Redis has the corresponding cached results.

The Demo address

After writing so much, I am still worried that there will be some problems when using the Demo, so I put the Demo on Github, everyone can download it.

SpringBoot – Redis – Demo address