SpringBoot integration Mybatis detailed process
Create a SpringBoot project
Add the Redis dependency package
<! -- Redis dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code
Configure the Redis database connection
Configure the redis database connection information in application.properties as follows:
#Redis server address
spring.redis.host=127.0.0.1
#Redis server connection port
spring.redis.port=6379
#Redis database index (default 0)
spring.redis.database=0
# maximum number of connections in the pool (use negative values to indicate no limit)
spring.redis.jedis.pool.max-active=50
Maximum connection pool blocking wait time (negative value indicates no limit)
spring.redis.jedis.pool.max-wait=3000
The maximum number of free connections in the connection pool
spring.redis.jedis.pool.max-idle=20
Minimum free connection in connection pool
spring.redis.jedis.pool.min-idle=2
Connection timeout (ms)
spring.redis.timeout=5000
Copy the code
Write Redis operation utility classes
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
/** * read cache **@param key
* @return* /
public Object get(final String key) {
return redisTemplate.opsForValue().get(key);
}
/** * write cache */
public boolean set( String key, Object value) {
boolean result = false;
try {
redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** * update the cache */
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** * delete cache */
public boolean delete(final String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
returnresult; }}Copy the code
test
@RunWith(SpringRunner.class)
@SpringBootTest
class BootmybatisApplicationTests {
@Autowired
private ArticleMapper articleMapper;
//写入,key:1,value:mysql数据库中id为1的article记录
@Autowired
private RedisUtils redisUtils;
@Test
void writeRedis(){
redisUtils.set("1",articleMapper.selectByPrimaryKey(1));
System.out.println("success");
}
@Test
void readRedis(){
Article article = (Article) redisUtils.get("1");
System.out.println(article);
}
}
Copy the code