在pom.xml 中引入如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在springboot-autoconfigure data-> redis 中的RedisAutoConfiguration 中如下源码
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
即没有ConditionalOnMissingBean 的时候向容易中注入bean
则只要在pom.xml 中加入对应的starter 即可在其他类中注入bean
测试代码如下:
@GetMapping("testkey")
public String getValueFromRedis(){
redisTemplate.opsForValue().set("name", "caiqiufang");
String name = (String) redisTemplate.opsForValue().get("name");
return name;
}
@GetMapping("testStringTemplate")
public String getValueFromRedis2(){
ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
String key = "spring.boot.redis.test";
if (!this.stringRedisTemplate.hasKey(key)) {
ops.set(key, "foo");
}
System.out.println("Found key " + key + ", value=" + ops.get(key));
return "Found key " + key + ", value=" + ops.get(key);
}
项目中使用Redis 作为缓存方法实现如下:
在springboot 主运行程序的上方标注如下
@SpringBootApplication
@EnableCaching //开启缓存
在一些方法上就可以使用如下来进行缓存,比如缓存权限菜单等
@GetMapping("/foo")
@Cacheable(value="getFoo")
public List<String> getFoo(){
System.out.println("如果redis 实现了缓存,那么再次访问的时候就不会出现这句话");
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
return list;
}