在分布式--Redis的安装与数据类型的使用和分布式--Redis持久化策略、主从复制、集群中我们搭建了Redis的环境,并使用了主从复制、哨兵、集群等功能,Redis环境有了,接下来就需要Java后端对Redis进行操作
对Redis的操作也可以使用Jedis库,但Spring公司集成了对各种NoSQL数据库操作,封装成了对应的启动器,这个项目叫SpringData,是Spring操作这些数据库的顶级项目
既然是启动器,那就很简单了,在pom
文件中导入启动器,并做一定的配置即可
SpringBoot项目中导入SpringDataRedis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
其他配置可以看以前的文章:SpringBoot--配置MyBatis、Logback、PagerHelper、Druid
核心配置文件中,添加redis的配置:
redis:
host: 192.168.42.4
cluster:
nodes: 192.168.42.4:7001,192.168.42.4:7002,192.168.42.4:7003,192.168.42.4:7004,192.168.42.4:7005,192.168.42.4:7006
# port: 7001
实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Serializable {
/**
* 部门编号
*/
private Integer deptno;
/**
* 部门名称
*/
private String dname;
/**
* 地址
*/
private String loc;
}
Redis配置类:
@Configuration
public class RedisConfigure {
@Bean
public RedisTemplate<String, List<Dept>> provideDeptRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, List<Dept>> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(List.class));
return redisTemplate;
}
}
public interface DeptMapper {
@Select("select * from dept")
List<Dept> findAllDept();
}
接口:
public interface DeptService {
List<Dept> findAllDept();
}
实现:
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private RedisTemplate<String, List<Dept>> redisTemplate;
@Autowired
private DeptMapper deptMapper;
@Override
public List<Dept> findAllDept() {
// 先从redis缓存中取
List<Dept> deptList = redisTemplate.opsForValue().get("dept");
if (deptList != null) {
System.out.println("从缓存中取");
return deptList;
}
System.out.println("从数据库中取");
List<Dept> allDept = deptMapper.findAllDept();
redisTemplate.opsForValue().set("dept", allDept);
return allDept;
}
}
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@RequestMapping("/getDept")
public List<Dept> getDept() {
return deptService.findAllDept();
}
}
@SpringBootApplication
@MapperScan("com/aruba/mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
访问效果: