SpringBoot整合Redis

1.创建一个SpringBoot项目,参考地址 http://www.cnblogs.com/i-tao/p/8878562.html

2.开启Redis服务器

./bin/redis-server redis.conf
ps -ef|grep redis

3.SpringBoot整合Redis

 3.1 在application.properties文件里面添加Redis服务器信息

#整合redis
spring.redis.host=192.168.*.*  //redis IP地址
spring.redis.port=6379            //端口号

 3.2 在项目pom.xml文件里面添加Redis依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.8.RELEASE</version>
</dependency>

 3.3 在项目入口开启Redis缓存@EnableCaching

package com.tao.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableCaching
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}

 3.4 在项目需要缓存的service层添加缓存@Cacheable

package com.tao.springboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.tao.springboot.mapper.UserMapper;
import com.tao.springboot.model.User;
import com.tao.springboot.service.UserService;
@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private UserMapper userMapper;

	@Override
	@Cacheable(value = "AllUser")//设置缓存
	public List<User> findAll() {
		// TODO Auto-generated method stub
		return userMapper.findAll();
	}
	
}
//常用缓存注解
@Cacheable//设置缓存 @CacheEvict//移除缓存 @CachePut//加入缓存

 3.5 启动SpringApplication

4.测试是否使用了缓存

 4.1 浏览器访问:http://localhost:8080/User/findAll

清空控制台重新刷新页面,数据不变,控制台没有日志输出

重启项目,清空日志,在访问一次。

 4.2 连接Redis客户端查询缓存是否存在:

./bin/redis-cli
keys *

SpringBoot整合Redis单机版本缓存结束。

原文地址:https://www.cnblogs.com/i-tao/p/8998740.html