1,修改sentinel.conf的配置文件
2,启动哨兵
3,配置文件
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/person?serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.17.4:26379
logging.level.com.example.springbootredishuancun.mapper=debug
4,实体类
package com.example.springbootredishuancun.eneity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName(value = "areainfo")
public class Person {
//默认查询的是id,我主键名叫areaid,所以加这个注解
@TableId(type = IdType.AUTO)
private Long areaid;
private String areaname;
}
5,mapper层
package com.example.springbootredishuancun.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootredishuancun.eneity.Person;
public interface PersonMapper extends BaseMapper<Person> {
}
6,service层
package com.example.springbootredishuancun.service;
import com.example.springbootredishuancun.eneity.Person;
import com.example.springbootredishuancun.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
@Service
public class PersonService {
@Autowired
private PersonMapper personMapper;
@Autowired
private RedisTemplate redisTemplate;
public Person selectById(Long areaid) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
ValueOperations valueOperations = redisTemplate.opsForValue();
//先从redis中获取数据
Object o = valueOperations.get("user::selectById::" + areaid);
//如果数据存在,直接从缓存返回,不走下一步
if (o != null) {
return (Person) o;
}
//如果不存在,查数据库,把查询的结果放到缓存中
else {
Person person = personMapper.selectById(areaid);
if (areaid != null) {
valueOperations.set("user::selectById::" + areaid, person);
}
return person;
}
}
}
7,控制层
package com.example.springbootredishuancun.controller;
import com.example.springbootredishuancun.eneity.Person;
import com.example.springbootredishuancun.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping("byId/{areaid}")
public Person byId(@PathVariable Long areaid){
return personService.selectById(areaid);
}
}