Để Spring boot có thể kết nối được đến Redis sentinel thì cần phải cấu hình trong file application.yml như sau:
application.yml
spring: cache: type: redis redis: sentinel: master: mymaster nodes: - redis-sentinel:26379 - redis-sentinel-1:26380 timeout: 1s lettuce: cluster: refresh: adaptive: true period: 5s
Trong class Application cần thêm vào annotation @EnableCaching:@SpringBootApplication @EnableCaching public class CustomerApplication { public static void main(String[] args) { SpringApplication.run(CustomerApplication.class, args); } }Trong class Service sử dụng các annotation @CacheEvict, @Cacheable để chỉ ra việc ghi
và đọc dữ liệu vào redis cache:
@Service public class CustomerServiceImpl implements CustomerService { @Autowired CustomerRepository customerRepository; @CacheEvict(value= "employeeCache", allEntries= true) @Override public boolean insertEmployee(CustomerVO customer) { Customer temp = new Customer(); temp.setName(customer.getName()); temp.setAddress(customer.getAddress()); Customer cust = customerRepository.save(temp); if(cust == null) { return false; } return true; } @CacheEvict(value= "employeeCache", allEntries= true) @Override public boolean updateEmployee(CustomerVO customer) { Customer temp = new Customer(); temp.setName(customer.getName()); temp.setAddress(customer.getAddress()); temp.setId(Long.parseLong(customer.getId())); Customer cust = customerRepository.saveAndFlush(temp); if(cust == null) { return false; } return true; } @Cacheable(value= "employeeCache", key= "#customerId") @Override public Customer getEmployee(String customerId) { Optional<Customer> cust = customerRepository.findById(Long.parseLong(customerId)); if(cust.isPresent()) { return cust.get(); } return null; } @Cacheable(value= "employeeCache", unless= "#result.size() == 0") @Override public List<Customer> getAllEmployee() { return customerRepository.findAll(); } }Chú ý rằng class Customer phải implement interface Serializable:
Full source code tại đây: https://github.com/WeLook-team/nguyen-giang-tip.blogspot.com/tree/main/Redis/redis-sentinel-master
@Entity @Table(name="customer") @EntityListeners(AuditingEntityListener.class) @JsonIgnoreProperties(allowGetters = true, ignoreUnknown = true) public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id() @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; @Column(name="name") private String name; @Column(name="address") private String address; public long getId() { return id; } public void setId(long id) { this.id = id; } 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; } }
No comments:
Post a Comment