Spring Boot cache trip (two)

Use Redis

1. Introducing a spring-boot-starter-data-redis-dependent

2. The project file configuration

Before using first start redis

#redis configuration 
#redis server address 
spring.redis.host = localhost 
#redis server port 
spring.redis.port = 6379 

# database configuration 
spring.datasource.driver - class -name = com.mysql.cj.jdbc.Driver 
spring.datasource .url = jdbc: MySQL: // localhost:? 3306 / characterEncoding the Test = UTF-8 & useSSL = false & serverTimezone% 2B8 = GMT = & allowPublicKeyRetrieval to true 
spring.datasource.username = root 
spring.datasource.password = 123456abc 

when ## validate load hibernate, verification create a database table structure 
## create each load hibernate, re-create the database table structure, which is the cause of the database tables of data loss. 
the Create ## -When you create a load hibernate drop, exit the delete table structure 
## update load hibernate automatically update the database structure 
does nothing when ## none start 
spring.jpa.hibernate.ddl -auto = the Create 

## console print SQL 
spring.jpa. Show -sql = to true

3. Use the set and get methods redis

@Service
public class RedisService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    //或者   这时不能有<String, Object>,这个特殊
//    @Autowired
//    private RedisTemplate redisTemplate;
    
    public void set(String key,Object value) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        ValueOperations<String, Object> vo=redisTemplate.opsForValue();
        vo.set(key, value);
    }
    
    public void set(String key,Object value,Long time,TimeUnit t) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        ValueOperations<String, Object> vo=redisTemplate.opsForValue();
        vo.set(key, value);
    }
    
    public Object get(String key) {
        ValueOperations<String, Object> vo=redisTemplate.opsForValue();
        return vo.get(key);
    }
}

4. User entity class and a write repository

5.Controller test

@RestController
public class UserController {
    @Autowired
    private RedisService redisService;

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "saveUser")
    public String saveUser(Long id, String userName, String userPassword) {
        User user = new User(id, userName, userPassword);
        redisService.set(id.toString(), user);
        return "success";
    }

    @GetMapping(value = "getUserById")
    public Object getUserById(Long id) {
        return redisService.get(id.toString());
    }

    @GetMapping("/saveUser2")
    public User saveUser2(Long id, String userName, String userPassword) {
        User user = new User(id, userName, userPassword);
        userRepository.save(user);
        return user;
    }

    @GetMapping(value = "getUser")
    public Object getUser(Long id) {
        Object object = redisService.get(id.toString());
        if (object == null) {
            object = (userRepository.findById(id)).get();
            if (object != null) {
                redisService.set(id.toString(), object, 100L, TimeUnit.SECONDS);
            }
        }
        return object;
    }
}

Attention to the key and value should be serialized.

Use Redis Cache

Just when just redis database use, and real environment generally conventional database-based, supplemented by redis database. redis usually plays the role of cache.

1. In a new class RedisService set the expiration time Method:

public void set(String key,Object value,Long time,TimeUnit t) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        ValueOperations<String, Object> vo=redisTemplate.opsForValue();
        vo.set(key, value);
    }

2. Two new method in the Controller class

@GetMapping("/saveUser2")
    public User saveUser2(Long id, String userName, String userPassword) {
        User user = new User(id, userName, userPassword);
        userRepository.save(user);
        return user;
    }

    @GetMapping(value = "getUser")
    public Object getUser(Long id) {
        Object object = redisService.get(id.toString());
        if (object == null) {
            object = (userRepository.findById(id)).get();
            if (object != null) {
                redisService.set(id.toString(), object, 100L, TimeUnit.SECONDS);
            }
        }
        return object;
    }
Test effective.

Guess you like

Origin www.cnblogs.com/xc-xinxue/p/12418040.html
Recommended