Background: Based on Practice 1, we use Redis as a cache.
(reprint please indicate source: cnblogs Coder-fang)
- Pom Added dependency:
< dependency > < groupid > org.springframework.boot</ groupid > < artifactid > Spring-boot-starter-data-redis</ artifactid > </ dependency >
- To add a configuration to the application.properties:
Spring.redis.host=127.0.0.1spring.redis.port=6379spring.redis.pool.max-idle=8spring.redis.pool.max-active=8
- Create the Redisconfig class and inject the redistemplate bean:
PackageCom.test.demo.config;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;Importorg.springframework.data.redis.connection.RedisConnectionFactory;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.data.redis.core.StringRedisTemplate; @Configuration Public classRedisconfig {@Bean PublicRedistemplate<string, string>redistemplate (Redisconnectionfactory factory) {stringredistemplate stringredistemplate=Newstringredistemplate (Factory); returnstringredistemplate; }}
- Implement Redisrepostory Universal functionality:
PackageCom.test.demo.db.repo.nosql;ImportJava.util.concurrent.TimeUnit;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.stereotype.Repository; @Repository Public classredisrepository {@Autowired redistemplate<string, string>redistemplate; Public voidAdd (String key,string value) {Redistemplate.opsforvalue (). Set (key, value); } Public voidAdd (String key,string value,long time) {Redistemplate.opsforvalue (). Set (key, value, time, timeunit.minutes); } Publicstring Get (String key) {returnRedistemplate.opsforvalue (). get (key); } Public voidDelete (String key) {Redistemplate.opsforvalue (). GetOperations (). Delete (key); } }
- To create a unit test and run:
PackageCom.test.demo;Import Staticorg.junit.Assert.assertEquals;Import StaticOrg.junit.Assert.assertNull;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner;Importcom.test.demo.db.repo.nosql.RedisRepository; the @RunWith (Springrunner.class) @SpringBootTest Public classredistest {@Autowired redisrepository redisrepo; @Test Public voidTestredis () {Redisrepo.add ("Test", "123", 1L); String Val= Redisrepo.get ("Test"); Assertequals (Val,"123"); System.out.println (Val); Val= Redisrepo.get ("321"); System.out.println (Val); Assertnull (Val); }}
View Code
YES, Redis is completed in the project.
Spring Boot Practice 2--using Redis in projects