步骤一:导入依赖包
<!-- redis 缓存 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>步骤二:
1. 单机版
在application.properties配置中加入
#spring.redis.host=192.168.0.111 #spring.redis.port=8023在spring boot 的启动类中开启redis 缓存
@SpringBootApplication // 开启redis 缓存 //@EnableCaching public class SpringDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringDemoApplication.class, args); } }开启缓存后就可以使用了:在需要用到缓存的地方加上注解即可
@Cacheable(value = "addUser")
/** * @Cacheable redis 缓存 * @param user */ // @Cacheable(value = "addUser") public void addUser(User user) { userMapper.addUser(user); }
2. redis 集群
在在application.properties配置中加入
#整合redis 集群 #spring.redis.cluster.nodes=192.168.0.108:7001,192.168.0.108:7002,192.168.0.108:7003,192.168.0.108:7004写一个配置文件用来分解以上集群节点
//@Configuration //public class RedisConfig { // // @Value("${spring.redis.cluster.nodes}") // private String clusterNodes; // // /** // * 注入集群节点信息 // * @return // */ // @Bean // 相当于<bean> // public JedisCluster getJedisCluster(){ // // // 分割集群节点 // String[] strings = clusterNodes.split(","); // // Set<HostAndPort> hostAndPorts = new HashSet<HostAndPort>(); // // // 循环集群节点对象 // for (String node : strings) { // String[] hp = node.split(":"); // // hostAndPorts.add(new HostAndPort(hp[0],Integer.parseInt(hp[1]))); // } // // // // JedisCluster jedisCluster = new JedisCluster(hostAndPorts); // // return jedisCluster; // } //}
使用的时候注入以下即可:
@Autowired // private JedisCluster jedisCluster;
// public String findRedis(){ // jedisCluster.set("name","sfsd"); // String value = jedisCluster.get("name"); // // return value; // }