SpringBoot 整合redis
1:redis 配置修改,保证外部服务可以连接
redis.conf:
吧绑定本地连接注释掉(默认是打开的)
保护模式改为no(默认是yes)
2:springboot整合redis
入口方法修改
//启用注解事物管理
//@EnableTransactionManagement
//@Configuration
//@EnableAutoConfiguration
//@ComponentScan
@MapperScan("com.jxd.Boot.mybatis.dao") // 启用mybatis
@SpringBootApplication //相当于上边几个的集合
//@EnableScheduling//开启定时任务注解
//@EnableCaching// 开启缓存,需要显示的指定(Ehcahe 使用redis应该去掉这个注解否则redis缓存不起作用)
@EnablePrometheusEndpoint//开启监控
@EnableSpringBootMetricsCollector//开启监控
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
pom.xml
<!--redis start-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!--redis end-->
redis配置文件
#redis config
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.221.129
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
获取redis配置&注入spring
package com.jxd.Boot.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.util.Arrays;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 多个缓存的名称,目前只定义了一个
rcm.setCacheNames(Arrays.asList("cache-one"));
//设置缓存过期时间(秒)
rcm.setDefaultExpiration(600);
return rcm;
}
/**
* 注入redistemplate 非注解情况下使用
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
测试controller(方法名是瞎写的,测试以实现功能为目的)
package com.jxd.Boot.web;
import com.alibaba.fastjson.JSONObject;
import com.jxd.Boot.config.RedisConfig;
import com.jxd.Boot.po.Student;
import com.jxd.Boot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
/**
* redis测试controller
* springboot 1.5.4.RELEASE版本
*/
@RestController
public class TestRedis {
@Autowired
private StudentService studentService;
/**
* 依赖注入 获取rediTemplate
*/
@Autowired
private RedisTemplate redisTemplate;
/***------------------------------注解使用------------------------------------------------------/
/**
* 测试redis缓存序列化实体类
* @param id
* @return
*/
@Cacheable(value = "cache-one",key = "#id")
@RequestMapping("/ffff")
public Student getjson(String id){
Student student = studentService.findByUid("001c2043-5352-46cf-9a1b-93ef92733152");
System.out.println("没有key");
return student;
}
/**
* 删除缓存数据
* @param id
* @return
*/
@CacheEvict(value = "cache-one",key = "#id")
@RequestMapping("/ddd")
public Object deleteKey(String id){
System.out.println("删除"+id+"成功....");
return new JSONObject();
}
/**
* 测试redis缓存非序列化对象
* @param id
* @return
*/
@Cacheable(value = "cache-one",key = "#id")
@RequestMapping("/bbb")
public Object getjson1(String id){
JSONObject json = new JSONObject();
json.put("name","进行");
System.out.println("没有key1");
return json;
}
/**
* @Cacheable(value = "cache-one",key = "mo") 会报以下异常
* org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'mo' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public?
* @return
*/
@Cacheable(value = "cache-one",key = "'mo'")
@RequestMapping("/aaa")
public Object getjson2(){
JSONObject json = new JSONObject();
json.put("name","进行1");
System.out.println("没有key11");
return json;
}
/**
* 测试查询数据库是否正常
* @return
*/
@RequestMapping("/aa")
public Object aa(){
Student student = studentService.findByUid("001c2043-5352-46cf-9a1b-93ef92733152");
return student;
}
/**-----------------------------------------------非注解使用-------------------------------------------------------------/
/**
* 非注解方式存数据到缓存
* @return
*/
@RequestMapping("/custor")
public Object testRediss(){
JSONObject json = new JSONObject();
json.put("a","金");
redisTemplate.opsForValue().set("custor",json);
return json;
}
/**
* 非注解方式获取缓存数据
* @return
*/
@RequestMapping("/getcustor")
public Object testgetRediss(){
JSONObject json = new JSONObject();
json= (JSONObject) redisTemplate.opsForValue().get("custor");
return json;
}
}
class Goods implements Serializable {
private static final long serialVersionUID = -6522574256668461033L;
private String name;
private String address;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}